← Full reference

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

CodeWhat it usually means
0success
1general error; for grep — "nothing found", for diff — "there are differences"
2incorrect usage: invalid option, syntax error; for grep — a read error
124timeout stopped the command because time ran out
126the file was found but isn't executable (no x)
127command not found (a typo, not in PATH)
128+Nthe process was killed by signal N
130128+2: interrupted with Ctrl+C (SIGINT)
137128+9: killed by SIGKILL — often the OOM killer
143128+15: terminated by SIGTERM
255exit -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

FormWhat it does
$?the last command's code; overwritten by every command, including echo and [[ ]]
a && bb if a returned 0
a || bb if a returned non-zero
a && b || cc runs if a or b fails — this is not if/else
! commandinvert 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 numberexit with the last command's code

set options

OptionWhat 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 pipefaila 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 pipefaila common start of a "strict" script
set -oshow 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

FormWhat it does
trap 'commands' EXITrun on any exit from the script: normal, via exit, via set -e
trap 'commands' ERRrun when a command returned non-zero (where set -e would fire)
trap 'commands' INT TERMcatch Ctrl+C and kill
trap '' INTignore the signal
trap - INTrestore the default handling
trap -pshow 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 of echo. Save rc=$? right away.
  • a && b || c is not if/else. If a succeeds and b fails, c runs too. For real branching write if.
  • set -e doesn't catch errors in conditions. A function called as f || echo fail runs entirely without errexit: failing commands inside it won't stop execution.
  • local x=$(cmd) and export x=$(cmd) hide the error: the code is that of local/export, i.e. 0. Split it: local x; x=$(cmd).
  • ((i++)) with i=0 returns 1, and set -e terminates the script. Write ((i+=1)) or i=$((i+1)).
  • Without pipefail an error in the middle of a pipeline is lost: false | true is a success.
  • exit in a subshell exits only the subshell. ( exit 1 ) or cmd | while …; do exit 1; done won't end the script.
  • A signal trap without exit doesn't end the script. trap 'echo stop' TERM catches kill, and the script keeps running. Add exit to the handler.

See also

conditions-loops · redirection · shellcheck · kill