Exit codes
$?, && and || chains, set -e/-u/-o pipefail, exit and trap — how a script finds out about errors
Every command returns a number from 0 to 255 when it finishes. 0 means success, anything else means an error or "no". if, &&, ||, while and every check in a script rely on this code.
Syntax
command; echo $? # the last command's exit code
command1 && command2 # the second only if the first succeeded
command1 || command2 # the second only if the first failed
exit N # exit the script with code N
return N # return from a function with code N
Common codes
| Code | What it usually means |
|---|---|
0 | success |
1 | general error; for grep — "nothing found", for diff — "there are differences" |
2 | incorrect usage: invalid option, syntax error; for grep — a read error |
124 | timeout stopped the command because time ran out |
126 | the file was found but isn't executable (no x) |
127 | command not found (a typo, not in PATH) |
128+N | the process was killed by signal N |
130 | 128+2: interrupted with Ctrl+C (SIGINT) |
137 | 128+9: killed by SIGKILL — often the OOM killer |
143 | 128+15: terminated by SIGTERM |
255 | exit -1 or a code out of range; for ssh — a connection error |
The code is taken modulo 256: exit 300 gives 44.
Operators and variables
| Form | What it does |
|---|---|
$? | the last command's code; overwritten by every command, including echo and [[ ]] |
a && b | b if a returned 0 |
a || b | b if a returned non-zero |
a && b || c | c runs if a or b fails — this is not if/else |
! command | invert the code: 0 → 1, non-zero → 0 |
${PIPESTATUS[@]} | codes of all parts of the last pipeline |
rc=$? | save the code right away, before it's overwritten |
command || true | "the error doesn't matter" — the code is always 0 |
exit without a number | exit with the last command's code |
set options
| Option | What it does |
|---|---|
set -e (-o errexit) | exit the script as soon as a command returns non-zero (with exceptions, see below) |
set -u (-o nounset) | referencing an unset variable is an error and exits |
set -o pipefail | a pipeline fails if any part of it fails, not just the last |
set -x (-o xtrace) | print each command before running it (with a + prefix) — debugging |
set -E (-o errtrace) | an ERR trap fires inside functions too |
set +e, set +x … | turn the option off |
set -euo pipefail | a common start of a "strict" script |
set -o | show the state of all options |
set -e does not fire if the command is: in an if/while/until condition, to the left of && or ||, after !, inside a pipeline (except the last part, unless pipefail is set).
trap
| Form | What it does |
|---|---|
trap 'commands' EXIT | run on any exit from the script: normal, via exit, via set -e |
trap 'commands' ERR | run when a command returned non-zero (where set -e would fire) |
trap 'commands' INT TERM | catch Ctrl+C and kill |
trap '' INT | ignore the signal |
trap - INT | restore the default handling |
trap -p | show the installed handlers |
SIGKILL (9) and SIGSTOP can't be caught.
Examples
# find out the code
ls /nope 2>/dev/null; echo $? # 2
grep -q zzz /etc/passwd; echo $? # 1 — not found
# run only if the previous step succeeded
mkdir -p /tmp/build && cd /tmp/build && echo "ready"
# a fallback on error
cd /some/dir || exit 1
# save the code and examine it
some_command
rc=$?
if (( rc != 0 )); then echo "failed with code $rc" >&2; fi
# check success and keep the output
if ! out=$(ls /nope 2>&1); then
echo "error: $out" >&2
fi
# strict mode at the top of a script
#!/bin/bash
set -euo pipefail
# with set -u — a default value for an optional variable
echo "${DEBUG:-0}"
# remove a temp file on any exit
tmp=$(mktemp)
trap 'rm -f "$tmp"' EXIT
# report where the script failed
set -eE
trap 'echo "error on line $LINENO" >&2' ERR
# exit code when killed by a signal
sleep 100 & kill $!; wait $!; echo $? # 143
Pitfalls
$?lives for one command.cmd; echo "status"; echo $?shows the code ofecho. Saverc=$?right away.a && b || cis not if/else. Ifasucceeds andbfails,cruns too. For real branching writeif.set -edoesn't catch errors in conditions. A function called asf || echo failruns entirely without errexit: failing commands inside it won't stop execution.local x=$(cmd)andexport x=$(cmd)hide the error: the code is that oflocal/export, i.e. 0. Split it:local x; x=$(cmd).((i++))withi=0returns 1, andset -eterminates the script. Write((i+=1))ori=$((i+1)).- Without
pipefailan error in the middle of a pipeline is lost:false | trueis a success. exitin a subshell exits only the subshell.( exit 1 )orcmd | while …; do exit 1; donewon't end the script.- A signal trap without
exitdoesn't end the script.trap 'echo stop' TERMcatcheskill, and the script keeps running. Addexitto the handler.