Lesson 4 of 7 · 11 min · Reliable scripts

Exit codes, error handling and safe scripts

Covers: Ubuntu 24.04 LTS, bash 5.2, ShellCheck 0.9. Updated 13 Nov 2026. Part of the DevOps Engineer roadmap.

What you will learn

  • What exit codes mean and which numbers have a special meaning
  • set -e, set -u, set -o pipefail: what each does and where set -e does not protect you
  • trap for cleanup on exit and on errors
  • Debugging with bash -x and checking scripts with ShellCheck
  • A template for a script you can trust in a pipeline

In simple words

By default a script keeps going even after one of its commands fails, like a cook who keeps cooking after dropping the main ingredient. In automation that is dangerous. This lesson shows how to make a script stop at the first problem, clean up after itself, and report honestly whether it worked.

Words to know

  • Exit code: the number a command returns: 0 for success, anything else for failure.
  • set -e: a setting that stops the script as soon as a command fails.
  • trap: a way to run clean-up steps when the script ends, even if it ended with an error.
  • Idempotent: safe to run twice: the second run changes nothing and breaks nothing.

Exit codes

Every command ends with a number from 0 to 255. 0 is success; non-zero is failure. CI systems, cron, systemd and other scripts decide solely on this number, so a script that prints "ERROR" but exits 0 is a script that lies.

Code Usual meaning
0 success
1 general error
2 wrong usage (a convention; also used by grep for errors)
126 found but not executable
127 command not found
128+n killed by signal n (130 = Ctrl+C, 137 = SIGKILL, 143 = SIGTERM)

Verified:

ls missing: 2        (ls: no such file)
grep none: 1         (grep: no match)
not found: 127
not executable: 126

$? holds the last command's code. Your script sets its own with exit N; with no argument exit uses the last command's status. In functions use return.

grep shows why codes are not just "ok/bad": 0 found, 1 not found, 2 error. Do not treat 1 as an error when "nothing found" is a normal answer.

The strict mode, and what it does

Many scripts start with:

#!/usr/bin/env bash
set -euo pipefail
  • -e (errexit): exit immediately when a command fails.
  • -u (nounset): treat use of an unset variable as an error.
  • -o pipefail: a pipeline fails if any command in it fails, not only the last.

The difference they make, run for real. Without any option the script keeps going after a failed cd, which can then run later commands in the wrong directory:

cd /nonexistent
echo "still running in $(pwd)"
set -u
echo "$UNSET_VAR"
unsafe.sh: line 2: cd: /nonexistent: No such file or directory
still running in /w
unsafe.sh: line 5: UNSET_VAR: unbound variable

With -u a typo in a variable name stops the script, instead of silently becoming an empty string (and rm -rf "$DIR/" becoming rm -rf /). And pipefail:

false | true; echo "no pipefail: $?"     # 0, the failure is hidden
set -o pipefail
false | true; echo "pipefail: $?"        # 1
no pipefail: 0
pipefail: 1

${PIPESTATUS[@]} holds every stage's code: for false | true | false it is 1 0 1.

Where set -e does NOT protect you

set -e has well-known exceptions, so it is a safety net, not a guarantee. Tested:

  1. Commands in a condition. A failing command in if cmd, while cmd, cmd || ... or cmd && ... does not exit. This includes a function called in such a position: all of its commands run with set -e effectively off. With f() { false; echo "still here"; } then f && echo ok, the output is still here and ok.
  2. local v=$(failing_command). The status of local (always 0) replaces the command's. Declare first, assign after: local v; v=$(cmd).
  3. Failures inside a pipeline other than the last command, unless pipefail is on.
  4. Subshells and $( ) in some positions behave differently.

Because of this, check important commands explicitly:

cp "$src" "$dst" || die "copy failed"

and when a failure is acceptable, say so: grep -q pattern file || true.

Cleanup with trap

trap 'commands' SIGNAL... runs commands when the script receives the signal or a pseudo-event. The one to know is EXIT: it runs when the script ends for any reason (success, exit, error under set -e, or SIGTERM if also trapped).

#!/usr/bin/env bash
set -euo pipefail
tmp=$(mktemp -d)
trap 'echo "cleaning $tmp"; rm -rf "$tmp"' EXIT
echo "work in $tmp"
false_cmd() { return 3; }
false_cmd
echo "never reached"
work in /tmp/tmp.lvI2bCdpx8
cleaning /tmp/tmp.lvI2bCdpx8

and the script's exit status was 3, with the cleanup still done. trap '...' ERR runs on a failing command and is good for reporting where it happened (with set -E so functions inherit it):

set -eE
trap 'echo "error on line $LINENO (status $?)" >&2' ERR
ls /nope
ls: cannot access '/nope': No such file or directory
error on line 5 (status 2)

To stop cleanly on termination, trap 'exit 143' TERM makes SIGTERM run the EXIT trap too. SIGKILL can never be trapped. If a script is the main process of a container, it must handle SIGTERM or docker stop waits 10 seconds and then kills it.

Finding bugs: bash -x and ShellCheck

bash -x script.sh (or set -x inside) prints every command, with expansions, before running it:

+ name=Asha
+ echo 'hi Asha'
hi Asha
+ n=3

Set PS4='+ line $LINENO: ' to add line numbers. Turn it on only around the part you are debugging; it can print secrets.

ShellCheck (sudo apt-get install shellcheck, or the web version) reads a script without running it and explains likely bugs. Real output on a careless script:

rm -rf $dir/*
       ^----^ SC2115 (warning): Use "${var:?}" to ensure this never expands to /* .
for f in $(ls *.txt); do echo $f; done
         ^---------^ SC2045 (error): Iterating over ls output is fragile. Use globs.
if [ $x = 1 ]; then echo hi; fi
     ^-- SC2154 (warning): x is referenced but not assigned.
cd /tmp
^-----^ SC2164 (warning): Use 'cd ... || exit' or 'cd ... || return' in case cd fails.

Every warning has a number you can look up on the ShellCheck wiki with an explanation and the fix. Run it in CI on all your scripts; it catches the mistakes in the previous lessons automatically.

A template to start from

#!/usr/bin/env bash
# deploy.sh - what this script does, in one line
set -euo pipefail

log() { printf '%s %s\n' "$(date +%T)" "$*" >&2; }
die() { log "ERROR: $*"; exit 1; }

cleanup() { [[ -n ${tmp:-} ]] && rm -rf "$tmp"; }
trap cleanup EXIT

main() {
  [[ $# -eq 1 ]] || die "usage: $0 <environment>"
  local env=$1
  command -v curl >/dev/null || die "curl is required"
  tmp=$(mktemp -d)
  log "deploying to $env"
  # ... real work here ...
}

main "$@"

Properties worth copying: strict mode, logging to stderr, die with a clear message, a cleanup trap, argument and tool checks up front, work inside main.

Also make scripts idempotent: running twice must be safe (mkdir -p, ln -sfn, "create if missing" checks). Pipelines retry, humans re-run, and a script that breaks on the second run is a risk.

Common mistakes

  • Relying on set -e as the only protection (see the exceptions).
  • exit 0 at the end of a script that swallows an earlier failure.
  • Ignoring cd failures.
  • Logging errors but exiting 0.
  • Leaving set -x on in scripts that handle passwords.
  • No trap, so temp files and half-done state remain after a failure.

Try it yourself

  1. Run ShellCheck on a script of yours (or the bad example above) and fix every finding.
  2. Write a script that creates a temp directory, then fails on purpose. Prove the directory is deleted anyway.
  3. Reproduce the local v=$(false) surprise, then fix it with the two-line form.
  4. Write a function retry that runs a command up to 3 times with a delay and returns the command's last exit status.

Check yourself

What do set -e, set -u and set -o pipefail each do?

-e exits when a command fails; -u makes unset variables an error; pipefail makes a pipeline's status that of the rightmost failing command instead of just the last one.

Why does cmd | tee log.txt hide a failure of cmd?

The pipeline's status is tee's, which succeeds. With set -o pipefail the failure of cmd becomes the pipeline's status; ${PIPESTATUS[0]} also gives it.

Name a case where set -e does not stop the script on a failure.

A command used as an if/while condition or on the left of &&/||; a failure in a function called there; local x=$(cmd); the non-final commands of a pipeline without pipefail.

What does trap '...' EXIT guarantee?

The commands run when the shell exits normally, via exit, or after an error under set -e, so cleanup happens. It does not run on SIGKILL.

Interview questions

What exit code does a script return if the last command fails, and how does a CI pipeline use it?

The code of that last command (unless exit sets another). CI marks a step failed on any non-zero code, so scripts must exit non-zero on every real failure.

How would you debug a script that fails only in CI?

Run it with bash -x (or set -x) to see each command, check the CI environment (PATH, working directory, missing tools, different shell), run ShellCheck, and reproduce locally in the same container image.

What is idempotency and why does it matter for scripts?

A script is idempotent if running it again has the same result as running it once. It makes retries and re-runs safe, which automation does all the time.

Summary

  • Exit 0 means success; 126, 127 and 128+n have fixed meanings; scripts must exit non-zero on failure.
  • Use set -euo pipefail as a safety net, know its exceptions, and check critical commands explicitly.
  • trap ... EXIT cleans up temporary state; trap ... ERR reports where an error happened.
  • Use bash -x to see what runs and ShellCheck to catch mistakes before they run.

Going deeper

See how much of this you can explain

A free mock interview asks you new questions on Shell scripting with Bash for DevOps Engineer and scores every answer, with what to fix.