Shell scripting in depth: Understanding return codes, the test command, and the if statement
brian_s 270002K5X3 Visits (3788)
This posting is all about return codes, the test command, and the if statement.
Here is a video covering this material as well:
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
Here are some examples of commands that have a non-zero return code (aka failure)
$ ls aoeu #Listing a file that doesn't exist
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:
$ test 4 -lt 6
The "if" statement
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.
A lot of scripts use something like this:
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: