Skip to content
$ lynuxpro
← Bash Scripting

LESSON 10 OF 17 · INTERMEDIATE · 20 MIN

Error handling and safe scripts

HOW IT WORKSStrict mode and cleanup

set -euo pipefailstrict mode
1/6

By default Bash keeps going after a failure. Strict mode at the top of every script changes that.

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

By default, Bash is very forgiving: if a command fails, it prints an error and carries on with the next line. If a variable name has a typo, Bash quietly uses an empty string. That is fine when you are typing interactively, and dangerous in automation, where a failed cd followed by rm -rf * deletes the wrong folder. This lesson turns your scripts from "hope it works" into "stops safely when something goes wrong".

In simple words

  • Strict mode: set -euo pipefail: stop on errors, on unset variables and on failures inside pipes.
  • trap: runs clean-up code when the script exits or is stopped, whatever the reason.
  • Temporary file: a scratch file made safely with mktemp and deleted at the end.
  • Lock: stops two copies of the same script running at once, often with flock.

The problem, demonstrated

printf '#!/usr/bin/env bash\ncd /does-not-exist\necho "now in: $(pwd)"\necho "cleaning up files here..."\n' > unsafe.shchmod +x unsafe.sh./unsafe.sh
SHELLbashutf-8 · 3L
./unsafe.sh: line 2: cd: /does-not-exist: No such file or directorynow in: /home/lynuxprocleaning up files here...
OUTPUTterminalutf-8 · 3L

The cd failed, but the script kept going and was about to "clean up" your home folder. Real incidents have happened exactly like this.

Strict mode: set -euo pipefail

Put this line directly under the shebang of every script:

#!/usr/bin/env bashset -euo pipefail
SHELLbashutf-8 · 2L

It turns on three options.

-e (errexit): stop on the first failure

If any command exits with a non-zero code, the script stops immediately with that code:

printf '#!/usr/bin/env bash\nset -e\ncd /does-not-exist\necho "this never runs"\n' > safe.shchmod +x safe.sh./safe.shecho "exit code: $?"
SHELLbashutf-8 · 4L
./safe.sh: line 3: cd: /does-not-exist: No such file or directoryexit code: 1
OUTPUTterminalutf-8 · 2L

-e does not stop the script for commands whose failure you are already handling: the condition of an if or while, anything followed by && or ||, and commands negated with !. That is what lets you write checks:

if grep -q web1 /etc/hosts; then …; fi   # a non-match does not exitgrep -q web9 /etc/hosts || echo "not found, continuing"
SHELLbashutf-8 · 2L

-u (nounset): unset variables are errors

printf '#!/usr/bin/env bash\nset -u\nbuild_dir=/tmp/build\necho "cleaning $biuld_dir"\n' > typo.shchmod +x typo.sh./typo.sh
SHELLbashutf-8 · 3L
./typo.sh: line 4: biuld_dir: unbound variable
OUTPUTterminalutf-8 · 1L

Without -u, that typo would expand to nothing. In a line like rm -rf "$biuld_dir/"* it becomes rm -rf /*. With -u, the script stops instead.

When a variable is genuinely optional, give it a default so -u is satisfied: "${DEBUG:-0}", "${1:-}".

-o pipefail: failures inside pipes count

As you saw in the previous lesson, a pipeline normally reports only the last command's exit code. pipefail makes the pipeline fail if any part of it fails, so -e can catch it.

Know the gaps in set -e

set -e is a safety net, not a guarantee. It is skipped in a few places that surprise people:

  • Inside a function called from an if condition, or followed by ||, failures do not stop the function.
  • local var=$(command) hides the command's failure, because the exit code becomes the exit code of local, which succeeded. Declare and assign separately:
local outout=$(curl -fsS "$url")       # failure now triggers -e
SHELLbashutf-8 · 2L
  • Arithmetic with (( )) that evaluates to 0 counts as failure: (( count++ )) when count is 0 exits the script. Use count=$((count + 1)) instead.

For important steps, check explicitly rather than relying on -e alone.

Explicit checks: || die

Combine || with a small die function for clear error messages:

die() { echo "ERROR: $*" >&2; exit 1; } cd "$release_dir"                || die "cannot enter $release_dir"tar -xzf "$artifact"             || die "could not extract $artifact"[[ -f config/app.env ]]          || die "config/app.env missing in release"
SHELLbashutf-8 · 5L

Each line says what it is trying to do and what happens if it fails, which makes logs easy to read at 3 a.m.

Validating required variables

${var:?message} stops the script with a message when a variable is unset or empty. It is perfect at the top of scripts that need environment variables:

printf '#!/usr/bin/env bash\n: "${DB_HOST:?DB_HOST must be set}"\necho "connecting to $DB_HOST"\n' > need-env.shchmod +x need-env.sh./need-env.shDB_HOST=db1 ./need-env.sh
SHELLbashutf-8 · 4L
./need-env.sh: line 2: DB_HOST: DB_HOST must be setconnecting to db1
OUTPUTterminalutf-8 · 2L

: is a built-in command that does nothing; it exists here only so the expansion runs.

trap: clean up no matter what

Scripts often create temporary files, take locks or start background processes. If the script stops halfway, through an error, exit or Ctrl+C, those should still be cleaned up. trap registers a command to run when the shell receives a signal or exits:

#!/usr/bin/env bashset -euo pipefail workdir=$(mktemp -d)cleanup() {  rm -rf "$workdir"  echo "cleaned up $workdir" >&2}trap cleanup EXIT echo "working in $workdir"cp /etc/hosts "$workdir/"false        # simulate a failure: the script stops here…echo "never printed"
SHELLbashutf-8 · 14L

…but cleanup still runs, because EXIT fires on every way out of the script. Try a compact version:

printf '#!/usr/bin/env bash\nset -e\ntmp=$(mktemp -d)\ntrap "echo cleaning up $tmp" EXIT\necho "working in $tmp"\nfalse\necho "never printed"\n' > trap-demo.shchmod +x trap-demo.sh./trap-demo.sh
SHELLbashutf-8 · 3L
working in /tmp/tmp.4f2a9c1e7bcleaning up /tmp/tmp.4f2a9c1e7b
OUTPUTterminalutf-8 · 2L

Useful signals to trap:

SignalWhen
EXITthe script ends for any reason (Bash-specific, the most useful)
ERRa command fails (with set -e, just before exiting)
INTCtrl+C
TERMkill, or a container or systemd stopping the process

Reporting where a failure happened

An ERR trap can print the line number and command that failed, which saves a lot of guessing:

trap 'echo "failed at line $LINENO: $BASH_COMMAND" >&2' ERR
SHELLbashutf-8 · 1L

Temporary files the safe way

Never use fixed names like /tmp/data.txt: two runs at once overwrite each other, and other users on the machine can predict the name. mktemp creates a unique file or folder:

tmpfile=$(mktemp)tmpdir=$(mktemp -d)echo "file: $tmpfile"echo "dir:  $tmpdir"
SHELLbashutf-8 · 4L

Pair it with trap … EXIT every time.

Preventing two copies running at once

Cron jobs and CI steps sometimes overlap: the 2:00 backup is still running when someone starts it by hand. flock takes a lock and exits if another copy holds it:

exec 9> /var/lock/backup.lockflock -n 9 || { echo "another backup is running, exiting" >&2; exit 0; }
SHELLbashutf-8 · 2L

The lock is released automatically when the script exits, even if it crashes.

Meaningful exit codes

Exit codes are how your script talks to cron, CI pipelines, systemd and monitoring. Use them deliberately:

readonly E_USAGE=2 E_CONFIG=3 E_REMOTE=4[[ $# -eq 1 ]]         || { usage; exit "$E_USAGE"; }[[ -r $config ]]       || { echo "cannot read $config" >&2; exit "$E_CONFIG"; }curl -fsS "$api" >/dev/null || exit "$E_REMOTE"
SHELLbashutf-8 · 4L

A pipeline can then react differently to "you called it wrong" and "the remote API is down".

A safe script template

This is a good starting point for any new script:

#!/usr/bin/env bash# what this script does, in one lineset -euo pipefailIFS=$'\n\t' readonly SCRIPT_NAME=${0##*/}log() { printf '[%s] %s\n' "$(date +%T)" "$*" >&2; }die() { log "ERROR: $*"; exit 1; }usage() { echo "usage: $SCRIPT_NAME ARG" >&2; exit 2; } cleanup() { [[ -n ${tmp:-} ]] && rm -rf "$tmp"; }trap cleanup EXITtrap 'log "failed at line $LINENO: $BASH_COMMAND"' ERR main() {  [[ $# -eq 1 ]] || usage  tmp=$(mktemp -d)  log "starting with $1"  # … work …  log "done"} main "$@"
SHELLbashutf-8 · 23L

IFS=$'\n\t' makes word splitting happen only on newlines and tabs, not spaces, which removes another class of filename bugs.

Real-world scenario: the release script that saved itself

A team's release script downloads an artifact, verifies its checksum, unpacks it into a new release folder and switches a symlink. One night the artifact server returned an HTML error page instead of the tarball:

curl -fsSLo "$tmp/app.tgz" "$url"           || die "download failed"sha256sum -c <<< "$expected  $tmp/app.tgz"  || die "checksum mismatch"tar -xzf "$tmp/app.tgz" -C "$release_dir"    || die "extract failed"ln -sfn "$release_dir" /srv/app/current
SHELLbashutf-8 · 4L

curl -f turned the HTTP error into a non-zero exit code, die stopped the script with a clear message, the EXIT trap removed the temp folder, and the current symlink was never touched. Production kept running the previous release. Without strict mode and checks, the script would have unpacked garbage and switched production to it.

Common mistakes

  • No set -euo pipefail in automation scripts.
  • local x=$(cmd), which hides failures. Split it into two lines.
  • (( n++ )) with set -e when n is 0.
  • Temp files with fixed names, or no trap to clean them up.
  • Swallowing errors with 2>/dev/null on commands that matter. Hide noise, not failures.
  • exit inside a function that runs in $( ): it only leaves the subshell, not the script.
  • Thinking set -e catches everything: important steps still deserve an explicit || die.

Practice

  1. Write a script without strict mode that runs ls /nope and then echo done. Add set -e and compare the behaviour and exit code.
  2. Add set -u to a script, misspell a variable on purpose, and read the error. Then fix it with a ${var:-default}.
  3. Create a script that makes a temp folder with mktemp -d, sets a trap that prints and removes it on EXIT, and then fails with false. Confirm the trap ran.
  4. Write a script that requires API_URL using ${API_URL:?…} and test it with and without the variable.

Cheat sheet

set -euo pipefail          strict mode (top of every script)cmd || die "message"       explicit check: "${VAR:?VAR is required}"   required variable"${VAR:-default}"          optional variable with -ulocal v; v=$(cmd)          keep failures visibletrap cleanup EXIT          always clean uptrap '…' ERR               report failures ($LINENO, $BASH_COMMAND)tmp=$(mktemp -d)           unique temp folderexec 9>lockfile; flock -n 9 || exit 0     single instanceexit 2 / 3 / 4             meaningful exit codes
OUTPUTterminalutf-8 · 10L

Key takeaways

  • Start every script with set -euo pipefail: stop on errors, on unset variables and on failures inside pipes.
  • set -e has gaps; protect important steps with || die "…".
  • Validate required input with ${VAR:?message} at the top.
  • Use mktemp for temporary files and trap … EXIT to clean up on every exit path.
  • Exit codes are your script's API for cron, CI and monitoring; choose them on purpose.