redirecting to /dev/null
No, this will not prevent the script from crashing. If any errors occur in the tar
process (e.g.: permission denied, no such file or directory, ...) the script will still crash.
This is because of using > /dev/null 2>&1
will redirect all your command output (both stdout
and stderr
) to /dev/null
, meaning no outputs are printed to the terminal.
By default:
stdin ==> fd 0
stdout ==> fd 1
stderr ==> fd 2
In the script, you use > /dev/null
causing:
stdin ==> fd 0
stdout ==> /dev/null
stderr ==> fd 2
And then 2>&1
causing:
stdin ==> fd 0
stdout ==> /dev/null
stderr ==> stdout
I'm trying to understand the use of "> /dev/null 2>&1" here.
(note that I added the redirection before /dev/null
in your question.)
The above would redirect the STDOUT
and STDERR
to /dev/null
. It works by merging the STDERR
into the STDOUT
. (Essentially all the output from the command would be redirected to the null device.)
... without causing the script to crash (kind of like try catch exception handling in programming languages).
It's not quite like a try/catch
or anything. It simply silences any sort of output (including error) from the command.
Because I don't see how using tar to compress a directory into a tar file could possibly cause any type of errors.
It could result in errors for a number of reasons, including:
- Inadequate permissions on the file(s) you're attempting to archive or on the file that you're attempting to write to
- Lack of disk space in order to create the archive
When you run CMD > /dev/null 2>&1
STDOUT redirects to /dev/null, and then STDERR redirects to THE ADDRESS of STDOUT, which has been set to /dev/null , consequently both STDOUT and STDERR point to /dev/null
Oppositely, when you run CMD 2>&1 >/dev/null
STDERR redirects to THE ADDRESS of STDOUT (File descriptor 1 in that moment, or /proc/self/fd/1), and then STDOUT redirects to /dev/null , but STDERR keeps redirecting to fd1!! As a result the normal output from STDOUT is discarded, but the errors coming from STDERR are still being written onto the console.