Module 1 · Lesson 58 of 103

Strict mode and traps

Make a script fail loudly with strict mode and clean up its temporary files on every exit path.

  • Beginner to advanced
  • 8 min read
  • 9 min lab
What you will need

Ubuntu 24.04 with Bash (WSL2, VM or container); ShellCheck installed; a Linux board for the BusyBox notes

Your place in the module
By the end you can 3 objectives
  • Explain how unquoted expansion and unchecked failures let a script fail silently.
  • Apply set -euo pipefail to make a script stop at the first failure
  • Use trap and mktemp so a script removes its temporary files on every exit path.
Video coming soonStrict mode and traps
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from Expansion layers, references and portability
  • Namerefs provide intentional access to caller variables and require controlled target names.
  • Check the board's interpreter and utilities before deploying Bash-specific features.
  • Command and process substitution do not propagate a producer's failure to the consumer command's status.
01

Scripts fail quietly by default

2 min read

The previous lesson used return and $? to read a command's status, but a script can still finish looking successful after a failure. This lesson answers why scripts fail quietly and how strict mode, traps, and mktemp make them fail fast and clean up.

Every command reports an after it runs. The previous lesson used return inside functions and saved $? to read a status. What it did not emphasise is that the shell itself does nothing with a failure by default. A script is just a list of commands, and the shell happily runs the next line even when the last one failed.

Imagine a maintenance script that runs on a board at 3 a.m. It is supposed to rotate a log file and then delete the old copy. If the rotation step fails, the script keeps going and deletes the only copy. The operator wakes up to a gap in the logs. The failure was silent: no message, no exit, no signal that anything went wrong.

The most common silent failure is . Consider this loop, which tries to process files by listing them:

bash
for f in $(ls data); do
    wc -l "$f"
done

A filename such as my file.txt contains a space. Unquoted $(ls data) splits the listing into separate words, so the loop receives my and file.txt as two filenames that do not exist. The output is wc: my: No such file or directory. Worse, if one step had deleted files based on the same broken list, the script would have removed the wrong paths. The bug is not that the shell is broken; it is that unquoted expansion was used where list boundaries mattered.

How a script fails silentlyRun commande.g. listfilesUnquotedexpansionWord splitson spacesFailureignoredNo set -eWrongresultNext lineuses brokenlistExit 0LookssuccessfulRun commande.g. listfilesUnquotedexpansionWord splitson spacesFailureignoredNo set -eWrongresultNext lineuses brokenlistExit 0Lookssuccessful
Unchecked failures and unquoted expansion compound silently into wrong results.

Three habits make failures loud. First, quote every expansion that must stay one argument. Second, enable options that stop the script on error. Third, test the script's exit status yourself, because a script that exits zero even when it failed is the worst kind of silent failure.

02

Fail fast with strict mode

3 min read

A Put this near the top of a script, right after the interpreter line:

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

The line sets three options at once. -e is errexit: exit immediately when a command fails. -u is nounset: treat an unset variable as an error. -o pipefail changes how a pipeline reports failure. Each is worth understanding alone.

1Understand each option

set -e makes the shell exit the moment a simple command returns a nonzero status:

bash
set -e
false
echo "never reached"

The script exits at false, before the echo runs. Without -e, the echo would run and the script would finish with status 0, looking successful.

set -u catches a different class of bug: a misspelled or never-set variable. Referencing an unset variable becomes an error and a non-interactive shell exits:

bash
set -u
echo "$UNDEFINED"
# bash: UNDEFINED: unbound variable

Without -u, $UNDEFINED expands to an empty string and the script carries on as if nothing happened. An empty string is rarely what you meant.

set -o pipefail fixes a classic surprise. Without it, a pipeline returns the status of its last command only:

bash
set -e
false | true
echo "survived"

The false command fails, but the pipeline's status is that of true, which is 0, so errexit sees success and the script continues. With pipefail, the pipeline fails if any command in it fails:

bash
set -euo pipefail
false | true
echo "never reached"

2Write the idiom once

The three options are normally written together because they reinforce each other. errexit stops on failure, nounset stops on unset variables, and pipefail stops when any link of a pipeline fails. set -u does not require -e, but a script that checks its variables yet ignores failed commands is only half safe.

Use the long spellings when you want the script to be self-documenting:

bash
set -o errexit -o nounset -o pipefail

set +e temporarily turns errexit off again, and set -e turns it back on. This is occasionally needed around a command you expect to fail, and the next section shows a cleaner way.

Three options, three channelsset -e(errexit)Exit on commandfailureset -u(nounset)Error on unsetvariableset -opipefailPipeline failson any linkTogether: set -euo pipefail
The three strict-mode options each close one channel that lets failures pass silently.
03

Clean up with traps and mktemp

5 min read

Long-running scripts need scratch space: a place to build a result before moving it into place, or to store intermediate output. The wrong way is a hard-coded name such as /tmp/mytmp. Two copies of the script running at once would collide, and an attacker could pre-create that path. The right way is mktemp.

mktemp prints a fresh, unique path and creates the file. mktemp -d creates a private directory. On Linux the directory gets permissions 0700, readable only by you:

0700 gives the owner read, write, and execute permissions and gives group and others none. For a directory, execute permits traversal; the mktemp directory is private to its owner.

  • octal: 0700
bash
workdir="$(mktemp -d)"
echo "$workdir"
# typical output (yours will differ): /tmp/tmp.6fXYkq9Zxw

Register a cleanup function to run on exit:

bash
#!/usr/bin/env bash
set -euo pipefail
workdir="$(mktemp -d)"
cleanup() {
    rm -rf "$workdir"
    printf 'removed %s\n' "$workdir" >&2
}
trap cleanup EXIT

printf 'working in %s\n' "$workdir"
# ... create files inside "$workdir" ...

trap cleanup EXIT means: run cleanup whenever the shell exits. That includes reaching the end of the script, calling exit, and being interrupted by Ctrl-C.

1Handle signals deliberately

Ctrl-C sends a named SIGINT. A script should clean up on that signal too. The subtle part is that adding trap '...' INT replaces the default action, which was to terminate. If the handler does not exit, the script keeps running after Ctrl-C, which surprises everyone.

The clean idiom is to keep cleanup on EXIT and make the signal handler simply exit, so the exit then triggers cleanup:

bash
trap cleanup EXIT
trap 'exit 1' INT TERM

Now Ctrl-C runs exit 1, and exit 1 runs cleanup through the EXIT trap. TERM covers kill with the default signal. The EXIT trap cannot run after SIGKILL (kill -9): that signal cannot be caught, and the process is stopped immediately with no chance to run any handler. Nothing you write can change that.

2Trap errors for location

A second use of trap is the ERR signal, which fires when a command fails under the same conditions where errexit would stop the script:

bash
trap 'printf "failed at line %s: %s\n" "$LINENO" "$BASH_COMMAND" >&2' ERR

The single quotes matter: the command is stored as text and evaluated each time the trap fires, so $LINENO and $BASH_COMMAND report the failing line and the failing command. This gives you the location of a failure in a long script, which a bare exit status never tells you.

There is also a DEBUG trap, which runs before every simple command. It is the mechanism behind tracing and is useful for inspecting a script a line at a time; use it sparingly because it fires very often.

Step by stepFrom scratch space to cleanup
  1. Create: Call mktemp -d and store the returned path in a variable.

  2. Register: Install a cleanup function on EXIT that removes the directory.

  3. Guard signals: Add an INT and TERM handler that exits, so cleanup still runs.

  4. Work: Build files inside the private directory using the stored path.

  5. Leave: Any exit path, normal or signaled, invokes cleanup exactly once.

  6. Verify: After a test run, confirm the directory is gone.

Going deeperSignals in long-running scripts

A script that runs for hours on a board can be stopped by an operator pressing Ctrl-C, by systemctl stop, or by a watchdog. systemd and kill send SIGTERM first and escalate to SIGKILL later. A cleanup that only runs on EXIT already covers SIGTERM, because the default SIGTERM action terminates the shell and the shell still runs its EXIT trap. The trap 'exit 1' INT TERM line exists so that a trapped signal still ends the script: once you install a handler for INT or TERM, the script will no longer terminate on its own, so the handler must exit explicitly. On a systemd-managed board service, always write your cleanup as an EXIT trap, because the service manager is the thing deciding when your process should stop.

Cleanup on every exitmktemp -dPrivate0700directorytrapcleanupEXITRegisterremovalDo workFilesinside thedirectoryExit pathEnd, error,or signalExit from step 3: Ctrl-C or TERMHandler exits, EXIT trap runsCleanuprunsDirectoryremovedmktemp -dPrivate0700directorytrapcleanupEXITRegisterremovalDo workFilesinside thedirectoryExit pathEnd, error,or signalExit from step 3: Ctrl-C orTERMHandler exits, EXIT traprunsCleanuprunsDirectoryremoved
A private mktemp directory is removed on every exit path through an EXIT trap.

Key takeaways

  • An unchecked failure travels to the next line; a quoted, checked failure stops the script.
  • The EXIT trap runs on every normal or signaled exit, but never on SIGKILL.
  • mktemp makes a unique, private path; a trap removes it, so nothing is left behind.
  • set -euo pipefail makes the shell stop at the first failed command, unset variable, or failed pipeline link
Reflect
  1. Explain to a colleague, in two sentences: explain how unquoted expansion and unchecked failures let a script fail silently.
  2. Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
  3. What surprised you when you ran the commands yourself?
On a real board

Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.

References and further reading

Find your next step

↑ ↓ to move · Enter to open · Esc to close