By default, a bash script keeps going even when a command fails, and treats a mistyped variable as empty text. Defensive scripting means turning on the safety switches, so the script stops at the first problem. Then, before it leaves, the script always cleans up: it removes the temporary files and folders it made. Picture a restaurant kitchen. The cook stops cooking the moment they find a spoiled ingredient: that's set -e, which stops the script at the first failing command. The kitchen is always cleaned at the end of the shift, whether the night went fine, something went wrong, or it closed early: that's trap ... EXIT, which runs the cleanup however the script ends.
The example script
This is backup.sh. Its job is to count the ERROR lines in app.log, then copy data.db to a backup folder:
#!/usr/bin/env bash
set -euo pipefail
TMP=$(mktemp -d)
trap 'echo "cleanup: remove $TMP"; rm -rf "$TMP"' EXIT
trap 'echo "ERROR on line $LINENO, exit $?" >&2' ERR
echo "1. count errors in the log"
grep ERROR app.log | wc -l
echo "2. copy the database"
cp data.db "$BACKUP_DIRR/"
echo "3. done"
Three problems are planted on purpose: app.log doesn't exist, BACKUP_DIRR is a typo (it should be BACKUP_DIR), and a normal user can't write to the / folder. Lines 2, 4 and 5 are the safety switches. On line 3, mktemp -d makes a temporary folder with a random name. $(...) puts that command's output (the folder's path) into TMP. First, let's see what happens without those three lines.
An exit code is the number every command leaves behind when it finishes: 0 means it worked, anything other than 0 means it failed. echo $? shows the exit code of the last command.
No safety switches: it keeps going
With lines 2, 4 and 5 removed, steps 1 and 2 will fail. Guess first: does the script still print 3. done? Is its exit code 0 or 1? Here is the output in bash on Linux:
$ bash backup.sh; echo "exit: $?"
1. count errors in the log
grep: app.log: No such file or directory
0
2. copy the database
cp: cannot create regular file '/data.db': Permission denied
3. done
exit: 0
Line numbers below are from the example script.
- Line 8:
grepfails, but a pipe's exit code comes from its last command,wc, which succeeded and counted 0 lines (that's the0in the output). So the exit code doesn't show thatgrepfailed. - Line 10:
$BACKUP_DIRRwas never set (given a value), so bash replaces it with empty text. The command becomescp data.db /, and it's refused. - Line 11: the script still prints
3. done, and its exit code is0. From the outside, this backup looks successful even though nothing was copied. The temporary folder frommktempis left behind too.
Three safety switches: set -euo pipefail
set -euo pipefail is the same as set -e -u -o pipefail. Here's what each switch does to backup.sh when it's the only one on:
| Switch | Meaning | What happens in backup.sh |
|---|---|---|
-e (exit on error) |
stop as soon as a command fails | stops at line 10 (cp), exit 1 |
-o pipefail |
a pipe fails when any part of it fails | line 8 now fails, with exit 2 from grep |
-u (undefined fails) |
an unset variable is an error, not empty text | line 10: backup.sh: line 10: BACKUP_DIRR: unbound variable |
-x (xtrace) |
print each command with a + in front before running it |
for debugging, it stops nothing |
With line 2 alone (without the two traps), the script stops at the first problem:
$ bash backup.sh; echo "exit: $?"
1. count errors in the log
grep: app.log: No such file or directory
0
exit: 2
The 0 is still printed, because both sides of a pipe run at the same time: wc still counts even though grep failed. The difference is that pipefail makes the pipe fail, and then -e stops the script there. Without pipefail, -e lets line 8 through and only stops at line 10.
-e deliberately doesn't apply where you test for success or failure:
- the condition of
ifandwhile, - a command on the left of
&&or||(||runs the right side only if the left failed), - a command whose result is flipped with
!.
So if grep -q ERROR app.log; then (-q: no output) stays safe: if grep finds no ERROR, the script doesn't stop.
Fallback values: ${VAR:-default}
With -u, a variable that's allowed to be missing needs a fallback, a value that is used when the variable is unset or empty:
PORT="${PORT:-3000}" # PORT empty or unset: use 3000
: "${DB_HOST:?DB_HOST must be set}" # stop with this message if it's empty
: is a command that does nothing. On the second line, : is only there so that bash checks ${DB_HOST:?...}.
What PORT holds |
${PORT:-3000} |
|---|---|
| not set | 3000 |
"" (empty) |
3000 |
8080 |
8080 |
The colon matters. ${PORT:-3000} uses the fallback for a variable that is unset and for one that is empty. Without the colon, ${PORT-3000} uses the fallback only when the variable is unset: empty text is used as it is.
trap: cleanup that always runs
trap 'command' EXIT runs that command when the script ends, whatever the reason: a normal finish, a stop from -e or -u, Ctrl+C, or kill. The only exception is kill -9, which can't be caught. trap '...' ERR runs every time a command fails. ERR doesn't need -e. But ERR doesn't run for a -u error, because bash leaves right away.
In backup.sh, the EXIT trap (line 4) removes the temporary folder. The ERR trap (line 5) prints the number of the line that failed ($LINENO) and its exit code ($?) to stderr (>&2). Here is the output with every switch on:
$ bash backup.sh; echo "exit: $?"
1. count errors in the log
grep: app.log: No such file or directory
0
ERROR on line 8, exit 2
cleanup: remove /tmp/tmp.k3J9qL2Abx
exit: 2
The order:
grepon line 8 fails, andpipefailmakes the pipe fail.- The ERR trap reports it.
-estops the script.- The EXIT trap cleans up.
The exit code is still 2. The trap doesn't change it.
Each event (EXIT, ERR or a signal) has only one trap: a second trap ... EXIT replaces the first. When several things need cleaning, gather them in one function. Undo them in reverse order: the last thing made is cleaned first. In this example, the script makes the $TMP folder first, then the $LOCK file:
cleanup() {
rm -f "$LOCK" # made last, cleaned first
rm -rf "$TMP" # made first, cleaned last
}
trap cleanup EXIT
⚠️ Safety switches that are only half on
set -ewithoutpipefail. A failure in the middle of a pipe doesn't stop the script, because a pipe's exit code comes from its last command.- A
grepthat finds nothing.grepexits with code 1 when no line matches, even though nothing is wrong. So whenapp.logexists but has no ERROR lines,grep ERROR app.log | wc -lstill stops the script (because ofpipefailand-e). Writegrep -c ERROR app.log || true.-ccounts the matching lines, so here it prints0. Whengrepfails,|| truerunstrue, a command that always succeeds, so that exit code 1 does not count as a failure. Note that|| truealso hides other errors, for example a missingapp.log:grepstill prints its error message, but the script continues. - A trap set too late. If the script fails before the
trapline, nothing cleans up. Set the trap right after the temporary folder is made. - Two
trap ... EXIT. The second one replaces the first. Put everything in onecleanupfunction. -uwith an optional variable. A variable that's allowed to be missing, such as$VERBOSE, stops the script when it's unset. Write${VERBOSE:-}(its fallback is empty text), or give it another fallback.
TL;DR: Put set -euo pipefail on the second line of every script. -e stops at the first failing command, -u refuses unset variables (never given a value), -o pipefail makes a pipe fail when any part of it fails, and -x prints each command for debugging. -e doesn't apply in if/while conditions or on the left of &&/||. For optional variables use ${VAR:-default}: the fallback is used when the variable is unset or empty. trap '...' EXIT runs its command when the script ends (success, failure, Ctrl+C), and trap '...' ERR runs every time a command fails. Each event has only one trap, so gather the cleanup (removing temporary files) in one function and clean up the last thing made first.
⚡ By default it keeps going
Guess first: backup.sh counts the errors in a log, copies a database, then prints "3. done". With no safety switches, its first two steps fail. Does the script still print "3. done"?
It does, and the exit code is 0 (success). From the outside, the backup looks like a success even though nothing was copied.
Meaning: By default, bash keeps going even when a command fails, and a mistyped variable is treated as empty text.
⚡ Three safety switches
Write:
#!/usr/bin/env bash
set -euo pipefail
Meaning: The safety switches go right after the shebang. -e stops at the first failing command. -u makes an unset variable (one never given a value) an error instead of empty text. -o pipefail makes a pipe (a chain joined with |) fail when any part of it fails.
⚡ Fallback values
Write:
PORT="${PORT:-3000}"
Meaning: With -u, a variable that may be empty needs a fallback value. If PORT is unset or empty, it becomes 3000.
⚡ Cleanup that always runs
Write:
TMP=$(mktemp -d)
trap 'rm -rf "$TMP"' EXIT
Meaning: mktemp -d makes a temporary folder, and TMP holds its path. trap ... EXIT runs rm -rf "$TMP" when the script ends, whatever the reason: a normal finish, a stop on error, or Ctrl+C. Set the trap right after the temporary folder is made.