TExcelTAD
Home › Linux & Bash › Exit Codes & Error Handling

Exit Codes & Error Handling

Every command reports success or failure through its exit status, a number from 0 to 255. By default Bash ignores failures and keeps going, which is how scripts end up deleting the wrong directory after a failed cd. This lesson shows how to check for errors and how to make scripts stop safely.

Exit status and $?

0 means success; anything else is failure. $? holds the status of the most recent command:

bash · try it yourself
ls /etc/passwd > /dev/null
echo "ls existing file: $?"
ls /no/such/file 2> /dev/null
echo "ls missing file:  $?"
grep -q root /etc/passwd; echo "grep found:       $?"
grep -q zebra /etc/passwd; echo "grep not found:   $?"
true; echo "true: $?"; false; echo "false: $?"
ls existing file: 0
ls missing file:  2
grep found:       0
grep not found:   1
true: 0
false: 1
Status Common meaning
0 Success
1 General error
2 Misuse: bad options or arguments
126 Found but not executable
127 Command not found
128+N Killed by signal N (130 = Ctrl+C, 137 = kill -9, 143 = kill)

Your own scripts set their status with exit N (and functions with return N). $? is overwritten by every command, even echo, so save it immediately if you need it later: status=$?.

Reacting to failures: && and ||

bash · try it yourself
mkdir -p build && echo "build directory ready"
cd /nonexistent 2> /dev/null || echo "cd failed, staying in $PWD"
cp missing.txt backup/ 2> /dev/null || { echo "copy failed" >&2; echo "(would exit here)"; }
build directory ready
cd failed, staying in /home/learner
copy failed
(would exit here)

cmd || exit 1 (or || die "message") is the simplest error handling and works everywhere.

set -e: stop at the first error

set -e (errexit) makes the script exit as soon as a command fails:

bash · try it yourself
cat > deploy.sh <<'SCRIPT'
set -e
echo "step 1: build"
cp app.tar.gz /tmp/release/
echo "step 2: this line never runs"
SCRIPT
bash deploy.sh
echo "deploy.sh exited with $?"
step 1: build
cp: cannot stat 'app.tar.gz': No such file or directory
deploy.sh exited with 1

set -e doesn't trigger for commands whose failure is "expected": conditions in if/while, commands followed by || or preceded by !, and all but the last command of && chains. So grep -q x file || true is fine under set -e.

set -u: unset variables are errors

A typo in a variable name normally gives an empty string silently. With set -u (nounset) it's an error:

bash · try it yourself
cat > cleanup.sh <<'SCRIPT'
set -u
build_dir="build"
echo "removing $biuld_dir/cache"
SCRIPT
bash cleanup.sh
echo "status: $?"
cleanup.sh: line 3: biuld_dir: unbound variable
status: 1

Without set -u this script would have tried to work on /cache. If a variable may legitimately be unset, give it a default: ${1:-} or ${NAME:-default}.

set -o pipefail

A pipeline's status is normally that of its last command, so failures earlier in the pipe are hidden. pipefail reports the last non-zero status in the pipeline instead:

bash · try it yourself
cat missing.log 2> /dev/null | sort | head -n 3
echo "without pipefail: $?"
set -o pipefail
cat missing.log 2> /dev/null | sort | head -n 3
echo "with pipefail:    $?"
without pipefail: 0
with pipefail:    1

The strict-mode header

Most robust Bash scripts start with these three options, often called strict mode:

bash
#!/usr/bin/env bash
set -euo pipefail

trap: cleanup and error reports

trap 'commands' SIGNAL runs code when something happens. EXIT runs whenever the script ends (success or failure), which is perfect for deleting temporary files. ERR runs when a command fails:

bash · try it yourself
cat > job.sh <<'SCRIPT'
set -euo pipefail
workdir=$(mktemp -d)
trap 'rm -rf "$workdir"; echo "cleanup done"' EXIT
trap 'echo "error on line $LINENO (status $?)" >&2' ERR
echo "working in a temp dir"
echo "data" > "$workdir/part1"
grep -q "total" "$workdir/part1"
echo "never printed"
SCRIPT
bash job.sh
echo "job.sh exited with $?"
working in a temp dir
error on line 7 (status 1)
cleanup done
job.sh exited with 1

The script failed on the grep (status 1: no line contains total), the ERR trap reported the line, and the EXIT trap still removed the temporary directory. (mktemp -d creates a uniquely named temporary directory; its random name is never printed here.)

Handling errors deliberately

Under set -e you still often want to handle a specific failure yourself:

bash · try it yourself
set -euo pipefail
config="app.conf"
if ! value=$(grep '^port=' "$config" 2> /dev/null); then
  echo "no port in $config, using 8080"
  value="port=8080"
fi
echo "${value#port=}"
count=$(grep -c ERROR /etc/hostname || true)
echo "errors: $count"
no port in app.conf, using 8080
8080
errors: 0

if ! cmd handles the failure without stopping the script. || true marks a failure as acceptable (grep -c exits with 1 when the count is 0).

Test yourself

What exit status means success?

  1. 1
  2. 0
  3. -1
  4. 255

Which option makes a pipeline fail when any command in it fails?

  1. set -e
  2. set -u
  3. set -o pipefail
  4. set -x

Which trap is the right place to delete temporary files?

  1. trap '...' ERR
  2. trap '...' EXIT
  3. trap '...' DEBUG
  4. trap '...' RETURN