Every command you run in a Linux/UNIX environment has a "return code" when the command completes. A zero (0) return code generally means the command was successful, and non-zero return code generally means failure. You can check the special $? variable to see the return code of the last command that was run.
Here are some examples of commands that return a zero return code (aka success):
$ ls testfile #Listing a file that exists testfile $ echo $? 0 #ls return code is 0, aka success $ true #The "true" command simply exits with a return code of 0 $ echo $? 0
Here are some examples of commands that have a non-zero return code (aka failure)
$ ls aoeu #Listing a file that doesn't exist ls: cannot access aoeu: No such file or directory $ echo $? 2 #Since the file didn't exist, ls has a non-zero return code $ false #The "false" command simply exists with a non-zero return code $ echo $? 1
The exclamation point, "!", reverses the return code. If you run "! false", the return code is "0". If you run "! true" the return code is 1. This is useful when you want to test for a situation that is not true.
The test Command:
You don't see the command "test" in scripts very often, but you frequently see statements such as: if [ "$var" == "value" ]; then ... The bracket "[" is just a shortcut for referring to the test command. The if [ "$var" == "value" ]; then ... is equivalent to if test "$var" == "value"; then ... So if you are trying to remember what options you have for comparisons, just run "man test" to list them. The test command plays by the same rules as other commands, it evaluates the statement and exits with a return code of either zero for success (the statement in question was true), or non-zero for failure (the statement in question was false). Here are some examples, using both the "test" syntax and the bracket "[" syntax:
There is a misconception about the "if" statement in shell scripting. Many people incorrectly think that you always have to do a bracket ("[") comparison when using the if statement (i.e. if [ 5 -lt 6]; then .... ) In fact, the if statement is much more flexible than that. The if statement runs whatever command is specified, and if the result is zero, the if statement code block is run; if the return code is non-zero the if statement code block is skipped.
if anycommand; then echo "anycommand had a zero return code"; fi
A lot of scripts use something like this:
grep somestring /tmp/test >/dev/null returncode=$? if [ "$returncode" -eq "0" ]; then echo "grep found string" fi
A simpler way to do it is just to put the grep command right in the if statement line. The following is simpler and easier to read, and does the exact same thing:
if grep somestring /tmp/test >/dev/null; then echo "grep found string" fi