Exit codes
From the "Advanced Bash-Scripting Guide":
Every command returns an exit status (sometimes referred to as a return status or exit code). A successful command returns a 0, while an unsuccessful one returns a non-zero value that usually may be interpreted as an error code. Well-behaved UNIX commands, programs, and utilities return a 0 exit code upon successful completion, though there are some exceptions.
After the execution of a program, the BASH sets the variable ? to the exit status of the last process executed:
$ ls /proc/meminfo /proc/meminfo $ echo $? 0
or:
$ ls /proc/Meminfo ls: cannot access /proc/Meminfo: No such file or directory $ echo $? 2
In line with the content of the ls man page, which laconically recites:
Exit status is 0 if OK, 1 if minor problems, 2 if serious trouble.
Keep in mind that although this 0 = success, non-0 = failure is a very widely used convention (that you should follow) it's not a rule and reading the manual of a program is always a good idea when relying on the exit status of a program.
The exit status of a program can be assigned to a variable, either directly (variable=program
) or using the $?
variable after the execution (program;variable=$?
) to avoid losing it at the execution of the next command, if required.