Return values

As shell scripts execute, it is important to confirm that their constituent commands complete successfully. Most commands offer a return value to the shell when they terminate. This value is a simple integer and has a meaning specific to the program you’re using. Almost all programs return the value 0 when they are successful and return a nonzero value when a problem is encountered. The value is stored in the special bash variable $?, which can be tested in your scripts to check for successful command execution. This variable is reset for every command executed by the shell, so you must test it immediately after execution of the command you’re verifying. As a simple example, try using the cat program on a nonexistent file:

$ cat bogus_file
cat: bogus_file: No such file or directory

Then immediately examine the status variable twice:

$ echo $?
$ echo $?

The first echo yielded 1 (failure) because the cat program failed to find the file you specified. The second echo yielded 0 (success) because the first echo command succeeded. A good script makes use of these status flags to exit gracefully in case of errors.

If it sounds backward to equate zero with success and nonzero with failure, consider how these results are used in practice:

Error detection

Scripts that check for errors include if-then code to evaluate a command’s return status:

if (failure_returned) ; then
  ...error recovery code...

In a bash script, failure_returned is examining the value of the $? variable, ...

Get LPI Linux Certification in a Nutshell, 3rd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.