An exit code (or exit status) is a small integer (0-255) that a program returns when it terminates, indicating success or the kind of failure. By convention, 0 means success and any non-zero value means failure. The shell exposes the last exit code in the special variable $?.
ls /nonexistent
echo $? # 2 (generic error)
true && echo yes # true returns 0, so echo runs
false || echo fail # false returns 1, so echo runs
Specific exit codes are not standardised beyond 0/non-zero, but many programs follow conventions: 1 for general error, 2 for misuse of shell command, 126 for command found but not executable, 127 for command not found, 128+N when killed by signal N. grep is unusual: 0 means a match was found, 1 means no match, 2 means an actual error.
In scripts, propagating exit codes correctly is essential. set -e causes the script to exit immediately on any non-zero exit code; combined with set -o pipefail, it also catches failures in the middle of pipelines. Functions can return values with return N, and the script's own exit code can be set with exit N. Understanding and respecting exit codes is the difference between a robust script and one that silently swallows errors.
Related terms: Shell Script, set -e, trap
Discussed in:
- Chapter 14: Shell Scripting — Error Handling
Also defined in: Textbook of Linux