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./unsafe.sh: line 2: cd: /does-not-exist: No such file or directorynow in: /home/lynuxprocleaning up files here...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 pipefailIt 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: $?"./safe.sh: line 3: cd: /does-not-exist: No such file or directoryexit code: 1-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"-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./typo.sh: line 4: biuld_dir: unbound variableWithout -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
ifcondition, 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 oflocal, which succeeded. Declare and assign separately:
local outout=$(curl -fsS "$url") # failure now triggers -e- Arithmetic with
(( ))that evaluates to 0 counts as failure:(( count++ ))whencountis 0 exits the script. Usecount=$((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"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./need-env.sh: line 2: DB_HOST: DB_HOST must be setconnecting to db1: 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"…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.shworking in /tmp/tmp.4f2a9c1e7bcleaning up /tmp/tmp.4f2a9c1e7bUseful signals to trap:
| Signal | When |
|---|---|
EXIT | the script ends for any reason (Bash-specific, the most useful) |
ERR | a command fails (with set -e, just before exiting) |
INT | Ctrl+C |
TERM | kill, 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' ERRTemporary 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"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; }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"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 "$@"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/currentcurl -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 pipefailin automation scripts. local x=$(cmd), which hides failures. Split it into two lines.(( n++ ))withset -ewhennis 0.- Temp files with fixed names, or no
trapto clean them up. - Swallowing errors with
2>/dev/nullon commands that matter. Hide noise, not failures. exitinside a function that runs in$( ): it only leaves the subshell, not the script.- Thinking
set -ecatches everything: important steps still deserve an explicit|| die.
Practice
- Write a script without strict mode that runs
ls /nopeand thenecho done. Addset -eand compare the behaviour and exit code. - Add
set -uto a script, misspell a variable on purpose, and read the error. Then fix it with a${var:-default}. - Create a script that makes a temp folder with
mktemp -d, sets atrapthat prints and removes it onEXIT, and then fails withfalse. Confirm the trap ran. - Write a script that requires
API_URLusing${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 codesKey takeaways
- Start every script with
set -euo pipefail: stop on errors, on unset variables and on failures inside pipes. set -ehas gaps; protect important steps with|| die "…".- Validate required input with
${VAR:?message}at the top. - Use
mktempfor temporary files andtrap … EXITto clean up on every exit path. - Exit codes are your script's API for cron, CI and monitoring; choose them on purpose.