Understanding Exit Codes
Every command that finishes in Bash leaves behind a small number called its exit code, also known as its exit status or return code. The number tells the caller whether the command succeeded and, if it failed, often what kind of failure happened. Conditions in if, the && and || operators, loops such as while, and error handling options such as set -e all work by looking at this number. Understanding exit codes is therefore the foundation for every error handling technique in the lessons that follow.
true
echo $?
false
echo $?
0
1
true is a command that does nothing and succeeds; false does nothing and fails. The special parameter $? holds the exit code of the most recent command (lesson 43 introduced it, and lesson 117 covers it in detail).
Zero Means Success
The central rule is simple and is the opposite of what many programmers expect from other languages:
| Exit code | Meaning |
|---|---|
0 | Success |
1 to 255 | Failure of some kind |
There is only one way to succeed and 255 ways to fail. This lets a program report different failure reasons with different numbers while keeping a single, unambiguous success value.
In languages such as C or Python, 0 is "false" in a boolean test. In the shell it is the other way round: a command whose status is 0 counts as "true" in if and while. The shell is not testing a value; it is asking "did this command succeed?"
if grep -q beta words.txt; then
echo "found beta"
fi
grep -q prints nothing; it only sets its exit code. if runs the then branch because grep returned 0.
Where the Number Comes From
An exit code is produced by the program itself when it ends. A C program returns it from main() or passes it to exit(); a Python program passes it to sys.exit(); a Bash script uses the exit builtin (lesson 118) or, if it has none, returns the status of the last command it ran. The operating system keeps the value and hands it to the parent process (here, the shell) when the parent waits for the child.
python3 -c 'import sys; sys.exit(4)'
echo $?
sh -c 'exit 3'
echo $?
4
3
The value travels between processes as a single byte, which is why the range is 0 to 255. A larger number is reduced to its remainder after division by 256:
bash -c 'exit 255'; echo $?
bash -c 'exit 256'; echo $?
bash -c 'exit 300'; echo $?
255
0
44
exit 256 reports success, which is almost never what the author intended. Keep exit codes between 0 and 255; in practice, small numbers are used.
Builtins and functions also produce exit codes, without any separate process. A function returns its status with return (lesson 90), and builtins such as cd or read set it directly.
Exit Codes of Common Commands
Most commands document their exit codes in their manual pages (lesson 23). Many follow the pattern "0 success, 1 a normal negative answer, 2 an error":
grep -q beta words.txt; echo "match: $?"
grep -q gamma words.txt; echo "no match: $?"
grep -q beta nofile.txt; echo "missing file: $?"
match: 0
no match: 1
grep: nofile.txt: No such file or directory
missing file: 2
For grep, "no match" (1) is not an error in the usual sense. It is an answer: the text is not there. Status 2 is a real problem, such as a file that cannot be read. A script that only checks for "non-zero" cannot tell these two situations apart, which is why the specific number matters.
diff follows the same idea:
| Command | 0 | 1 | 2 |
|---|---|---|---|
grep | a line matched | no line matched | an error occurred |
diff | files are the same | files differ | trouble (for example, a missing file) |
test / [ ] | condition true | condition false | invalid expression |
GNU ls | success | minor problem (for example, a subdirectory could not be read) | serious trouble (for example, a command-line argument that does not exist) |
[ 5 -gt 3 ]; echo $?
[ 5 -gt 9 ]; echo $?
[ 5 -gt x ]; echo $?
0
1
bash: [: x: integer expression expected
2
Other well-known values: timeout returns 124 when it had to stop the command (lesson 142), and xargs returns 123 when one of the commands it ran failed (lesson 112).
Exit Codes Set by the Shell
Some codes are not chosen by the program at all, because the program never started or did not end normally. Bash sets these itself.
127: Command Not Found
nosuchcmd
echo $?
./missing.sh
echo $?
bash: nosuchcmd: command not found
127
bash: ./missing.sh: No such file or directory
127
Status 127 means Bash could not find anything to run: the name is not a builtin, function or alias, and no file with that name exists in PATH or at the given path.
126: Found but Cannot Run
printf 'echo hi\n' > noexec.sh
chmod 644 noexec.sh
./noexec.sh
echo $?
mkdir -p adir
./adir
echo $?
bash: ./noexec.sh: Permission denied
126
bash: ./adir: Is a directory
126
Status 126 means the file exists, but it could not be executed, usually because the execute permission is missing (lesson 27) or the path is a directory.
2: Misuse of a Builtin and Syntax Errors
Bash builtins return 2 when they are called with an invalid option, and a script that fails to parse ends with 2:
read -Z x
echo $?
bash -c 'syntax error ('
echo $?
bash: read: -Z: invalid option
read: usage: read [-ers] [-a array] [-d delim] [-i text] [-n nchars] [-N nchars] [-p prompt] [-t timeout] [-u fd] [name ...]
2
bash: -c: line 1: syntax error near unexpected token `('
bash: -c: line 1: `syntax error ('
2
Not every builtin error gives 2. cd a b c prints cd: too many arguments and returns 1. The manual page or help text of each builtin is the authority.
128 + N: Killed by a Signal
When a process is stopped by a signal (lessons 139 to 141), it does not exit with a code of its own. Bash reports 128 plus the signal number:
sleep 10 & pid=$!
kill -TERM "$pid"
wait "$pid"
echo $?
143
SIGTERM is signal 15, so the status is 128 + 15 = 143. kill -l converts a status above 128 back into a signal name:
kill -l 143
kill -l 130
kill -l 141
TERM
INT
PIPE
| Status | Signal | Typical cause |
|---|---|---|
| 129 | SIGHUP (1) | The terminal was closed |
| 130 | SIGINT (2) | The user pressed Ctrl + C |
| 137 | SIGKILL (9) | kill -9, or the system's out-of-memory killer |
| 141 | SIGPIPE (13) | The command wrote to a pipe whose reader had already exited |
| 143 | SIGTERM (15) | A normal kill, or a service manager stopping the process |
Status 141 appears in ordinary pipelines and is usually harmless:
yes | head -n 1 > /dev/null
echo "${PIPESTATUS[*]}"
141 0
head exits after one line, and the next write by yes kills it with SIGPIPE. PIPESTATUS (lesson 61) shows each command's status. Lesson 120 explains why this matters for set -o pipefail.
Conventional Exit Code Values
| Code | Conventional meaning |
|---|---|
| 0 | Success |
| 1 | General failure, or a "no" answer (grep found nothing, false) |
| 2 | Incorrect usage, invalid option, or a serious error |
| 64-78 | Specific errors defined in sysexits.h (used by some programs) |
| 124 | timeout stopped the command |
| 126 | Command found but not executable |
| 127 | Command not found |
| 128 + N | Terminated by signal N |
| 255 | The highest value; ssh, for example, uses it for its own connection errors |
The values 64 to 78 come from the C header file /usr/include/sysexits.h, originally from BSD mail software. They give names to common failure types:
grep -E 'EX_(USAGE|NOINPUT|SOFTWARE|CONFIG)' /usr/include/sysexits.h
#define EX_USAGE 64 /* command line usage error */
#define EX_NOINPUT 66 /* cannot open input */
#define EX_SOFTWARE 70 /* internal software error */
#define EX_CONFIG 78 /* configuration error */
Few shell scripts use these numbers, and nothing enforces them. They are useful when a script wants a documented, recognizable set of codes.
Exit Codes of Shell Constructs
Compound commands and lists have exit codes too, and the rules are consistent:
| Construct | Exit code |
|---|---|
A pipeline a | b | The status of the last command, unless pipefail is set (lesson 120) |
! command | 0 if the command failed, 1 if it succeeded |
{ list; } and ( list ) | The status of the last command in the list |
if with no branch taken | 0 |
| A loop whose body never ran | 0 |
A plain assignment x=5 | 0 |
An assignment with command substitution x=$(cmd) | The status of cmd |
| A function | The value given to return, or the status of its last command |
| A script | The value given to exit, or the status of its last command |
false | true; echo "false | true -> $?"
true | false; echo "true | false -> $?"
! false; echo "! false -> $?"
( exit 7 ); echo "( exit 7 ) -> $?"
x=$(exit 5); echo "x=\$(exit 5) -> $?"
if false; then :; fi; echo "if with no branch -> $?"
false | true -> 0
true | false -> 1
! false -> 0
( exit 7 ) -> 7
x=$(exit 5) -> 5
if with no branch -> 0
The last rule in the table explains a frequent surprise. A script with no exit statement reports the status of whatever ran last:
printf 'echo working\nfalse\n' > last.sh
bash last.sh; echo "status $?"
printf 'false\necho done\n' > last2.sh
bash last2.sh; echo "status $?"
working
status 1
done
status 0
The second script failed in its first line but reports success, because echo done succeeded. Exit codes are not accumulated; only the last one counts. Lessons 117 to 122 show how to notice a failure in the middle of a script.
Designing Exit Codes for Your Own Scripts
Other programs, schedulers such as cron (lesson 170), CI pipelines (lesson 177) and the person at the terminal all judge a script by its exit code. A script that prints "error" but exits with 0 is reported as successful everywhere.
This small checker uses three distinct codes, documented at the top so that callers can rely on them:
#!/usr/bin/env bash
# report.sh - check a log file for ERROR lines
# Exit codes: 0 no errors, 1 errors found, 2 file cannot be read
if [ ! -r "$1" ]; then
echo "report: cannot read $1" >&2
exit 2
fi
if ! grep -q ERROR "$1"; then
echo "no errors"
exit 0
fi
echo "errors found:"
grep -c ERROR "$1"
exit 1
printf 'INFO ok\nERROR disk\nERROR net\n' > app.log
printf 'INFO ok\n' > clean.log
./report.sh clean.log; echo "status $?"
./report.sh app.log; echo "status $?"
./report.sh none.log; echo "status $?"
no errors
status 0
errors found:
2
status 1
report: cannot read none.log
status 2
Like grep, it separates "the answer is no" (1) from "something went wrong" (2). A caller can act on each case:
./report.sh app.log > /dev/null
case $? in
0) echo "clean" ;;
1) echo "has errors" ;;
*) echo "could not check" ;;
esac
has errors
The * branch catches every other code, including ones the script may add later and 126 or 127 if the script itself could not be started.
Guidelines that follow from the conventions above:
- Exit with 0 only when the script did what it was asked to do.
- Use 1 for a general failure and 2 for wrong usage, matching most command-line tools.
- If more codes are needed, pick small numbers below 126 and document them.
- Avoid 126, 127 and values above 128, which callers will read as "could not run" or "killed by a signal".
- Send error messages to standard error (lesson 59) so that the exit code and the message both reach the caller without mixing with normal output.
The examples were run with Bash 5.2.21, GNU grep 3.11, GNU diffutils, GNU coreutils 9.4, Dash and Python 3. Error messages are shown in their interactive form; inside a script, Bash adds the script name and line number in front.