Quote:
Originally posted by elyk
I've seen chunks of code in lots of scripts that look something like this:
Code:
if ! ..... 1> /dev/null 2> /dev/null ; then
What does this do? It looks like some kind of comparison, but it dumps everything in /dev/null. I don't understand.
|
Quote:
Doesn't 2> redirect stderr? If so, this redirects stdout and stderr to /dev/null, so shouldn't this always give you nothing?
|
Yes, all output from the command in the
if-statement gets discarded this way. But the output is not what "
if" uses to decide to execute some other commands or not. It is the
exit-code from the program that matters for the
if-statement. More precise: the exit-code of the
last command inside the if-statement.
The exit-code is a number from 0 to 127 each program returns to its parent process (often the shell) when it ends. By convention exit-code 0 (zero) is returned when the program ran succesfully, and some other exit-code (non-zero) when some error ocurred, or when the program did not succeed in some other way.
You can see the exit-code of the last command executed in bash with "echo $?". Example:
Code:
ls /does_not_exist
echo $?
ls /proc/uptime
echo $?
As you see, apart from the output of
ls it returns
1 when there was an error, so
ls didn't succeed, and
1 when
ls ran fine.
When you want a script to do something if a file or directory exists, you normally do:
Code:
if test -e /tmp/some_file ; then
# ...
fi
Here, "test" is a program that checks if the file or directory exist, and return an exit-code of 0 or 1 depending on whether the file /tmp/some_file exists or not. Note that the "test" program doesn't do any output. It is the exit-code that matters to the "
if" statement.
Also note that when you do this instead:
Code:
if [ -e /tmp/some_file ] ; then
# ...
fi
You should think of "
[" being a program that returns an exit-code ( "[" actually is a bash-builtin command, as is "test" by the way).
Another way to check whether a file (or directory) exists in a bash-script could be:
Code:
if ls /tmp/some_file >/dev/null 2>&1 ; then
# ...
fi
The output of the "ls" command is directed to /dev/null to prevent it from appearing as output from the script. It's the exit-code what is needed by the "if" in the script.