The Analogy: The Furnace Purge Cycle and the Emergency Stop
An industrial furnace does not simply switch off. Before the burner shuts down, the control system runs a purge cycle: the fans keep spinning for a fixed interval and sweep every trace of unburned fuel-air mixture out of the hot chamber, so that nothing lingers to ignite when the furnace next fires. The purge is not an optional courtesy. It runs at the end of every firing, and the burner is physically prevented from relighting until it has completed.
What makes the purge trustworthy is that it runs no matter how the firing ends. A scheduled stop at the end of a shift triggers it; so does a flame-failure trip; so does an operator slamming the red emergency-stop palm button on the wall. The controller wires the purge to the shutdown event itself, not to the tidy "normal end of run," because the abnormal stops are exactly the ones where raw gas is most likely to be left in a hot box. Skip the purge on an abrupt stop and the next ignition is an explosion.
A shell script runs the same risk in miniature. It acquires things that must be given back: a temporary file, a lock directory, a half-written output that should not be left behind. Those resources must be released whether the script finishes cleanly, dies on an error, or is interrupted by Ctrl-C or a kill from another process. The trap builtin is how you wire a cleanup routine to the exit event and to specific signals, exactly as the furnace wires its purge to shutdown. The EXIT trap is the purge that always runs; signal traps are the deliberate responses to specific trips like the emergency stop.
The failure mode is a purge that itself assumes an orderly stop. If the purge logic depends on the main controller still being powered, and the emergency stop is what cut that power, then the purge cannot complete and the one abnormal shutdown it exists to protect against is the one it cannot handle. Cleanup code fails the same way: a handler that assumes the resource it frees is in a known-good state, or that can itself be interrupted halfway by a second signal, breaks precisely when the interruption it was written for finally arrives.
Syntax or Core Structure
The trap builtin binds a command to one or more events: trap 'ACTION' SIGNAL.... The most useful event is not a real signal at all but the pseudo-signal EXIT, which fires whenever the shell exits for any reason. A cleanup registered on EXIT runs on a normal exit, on an error exit, and after a caught signal handler returns:
cleanup() { echo "cleanup ran"; }
trap cleanup EXIT
echo "working"
exit 0
Output:
working
cleanup ran
The script prints working, reaches exit 0, and on the way out the shell runs the trap, printing cleanup ran. You register the trap once, near the top, and never have to remember to call cleanup by hand at each exit point. That is the whole value: the guarantee holds even for exits you did not write.
The classic use is a temporary file that must not be left behind. Create it, register its removal on EXIT in the very next line, and then forget about it:
tmp=$(mktemp)
trap 'rm -f "$tmp"; echo "removed temp"' EXIT
echo "data" > "$tmp"
echo "temp exists: $([ -f "$tmp" ] && echo yes)"
Output:
temp exists: yes
removed temp
While the script runs the file exists; the moment it exits, the trap removes it. Registering the trap immediately after mktemp -- not later -- is what closes the window in which an early error could leak the file. Real signals such as INT (Ctrl-C) and TERM (the default kill) can be trapped by name in the same way, which the next section puts to work.
Technical Depth: The Exit Event, Signals, and the ERR Trap
EXIT runs however the script ends
The reason EXIT is the workhorse is that it fires on the paths you are most likely to forget: the error paths. Combine it with set -e and a failing command mid-script still triggers the cleanup on the way out:
trap 'echo "cleanup ran"' EXIT
set -e
echo "before"
false
echo "after"
Output:
before
cleanup ran
echo "before" runs, false returns non-zero, and set -e aborts the script. echo "after" never executes -- but the EXIT trap still does, so the cleanup runs and the script leaves with status 1. This is the property that makes traps worth the trouble: the guarantee is strongest exactly when the script is failing, which is when hand-written cleanup at the bottom would have been skipped entirely.
Catching interruptions
A long-running script should not die mid-write when someone presses Ctrl-C or a supervisor sends kill. Trapping the interrupt signals lets you shut down on your own terms. The signals you will actually handle are few:
| Signal | Number | Sent by | Default action |
|---|---|---|---|
| INT | 2 | Ctrl-C at the terminal | terminate |
| TERM | 15 | kill with no option | terminate |
| HUP | 1 | terminal closed or hangup | terminate |
| KILL | 9 | kill -9 | terminate, cannot be trapped |
| EXIT | n/a | the shell itself exiting | pseudo-signal, always runs |
A handler catches the signal, does the minimum needed to leave things safe, and exits with a status that records how it died. Here the script signals itself so the behaviour is reproducible:
trap 'echo "received TERM; shutting down"; exit 143' TERM
echo "started"
kill -TERM $$
echo "never reached"
Output:
started
received TERM; shutting down
$$ is the script's own process id, so kill -TERM $$ delivers a TERM to itself. Bash finishes the current command, then runs the trap: it prints the shutdown message and exits 143, so echo "never reached" is skipped. The exit code follows the convention 128 plus the signal number (128 + 15 = 143), which lets a caller tell a signal death from an ordinary failure. Note that KILL (9) is absent from what you can trap: the kernel delivers it unconditionally, which is why a cleanup you truly cannot skip belongs on EXIT, not on a signal handler.
The ERR trap and errtrace
Alongside EXIT and the signals sits ERR, which fires whenever a command would trip set -e. It is the place to report what failed before the script unwinds. On its own, though, ERR is not inherited by shell functions -- a failure inside a function will not fire it -- so you pair it with set -E (also spelled set -o errtrace):
set -eE
trap 'echo "ERR at command: $BASH_COMMAND"' ERR
f() { false; }
f
Output:
ERR at command: false
The false inside f trips the trap, and $BASH_COMMAND names the offending command. Drop the E from set -eE and the identical script prints nothing before exiting: the function boundary swallows the ERR trap. That single capital letter is the difference between an error report that covers your whole program and one that quietly stops at the first function call, which is why set -Eeuo pipefail is the fuller form of the incantation from the previous topic.
Real World Example: A Staging Build That Always Cleans Up
A build that assembles a release in a scratch directory must delete that directory whether the build succeeds, fails a step, or is interrupted. stage.sh wires cleanup to EXIT so it cannot be skipped, and routes INT and TERM into a deliberate abort. The workspace variable starts empty and the cleanup guards on it, so the trap is safe even if the script dies before the workspace exists:
#!/usr/bin/env bash
# stage.sh -- assemble a release in a temp workspace, cleaning up no matter how we exit
set -euo pipefail
workdir=""
cleanup() {
if [ -n "$workdir" ] && [ -d "$workdir" ]; then
rm -rf "$workdir"
echo "cleaned up workspace"
fi
}
trap cleanup EXIT
trap 'echo "interrupted; aborting"; exit 130' INT TERM
workdir="$(mktemp -d)"
echo "staging in workspace"
echo "payload" > "$workdir/artifact"
echo "built artifact"
if [ "${FAIL:-0}" = "1" ]; then
echo "simulating a mid-build failure"
false
fi
echo "release ready"
bash stage.sh
Output:
staging in workspace
built artifact
release ready
cleaned up workspace
On the happy path the build runs top to bottom, and the last line of output is the trap firing: cleaned up workspace is printed by cleanup on the way out, not by the body of the script. The body never calls cleanup itself; it only registered it. Force a failure and the same guarantee holds:
FAIL=1 bash stage.sh
Output:
staging in workspace
built artifact
simulating a mid-build failure
cleaned up workspace
With FAIL set, false runs after the artifact is built, set -e aborts the script, and release ready is never printed -- yet cleaned up workspace still appears, because the EXIT trap runs on the error path too. The script leaves with status 1, the workspace is gone, and nothing leaks. An interrupt behaves the same way: the INT/TERM handler prints its message and calls exit 130, which in turn triggers the EXIT trap, so the temp directory is removed even when the operator hits Ctrl-C.
The script is careful but not bulletproof, and the gaps are worth naming. There is a real race between mktemp -d creating the directory and the assignment to workdir: a signal delivered in that instant leaves a directory on disk that cleanup cannot see, because workdir is still empty. The cleanup itself is not protected against a second signal -- a kill arriving while rm -rf is mid-flight can interrupt the removal, leaving a partly-deleted workspace. And rm -rf "$workdir" is a loaded command: the -n and -d guards are all that stand between it and disaster should workdir ever hold an empty string or /. A hardened version would block signals during cleanup with trap '' INT TERM and create the directory and record its name as a single indivisible step.
Common Mistakes
- Assuming the EXIT trap does not run when the script fails. Under
set -ea failing command aborts the script, but theEXITtrap still fires on the way out. TreatEXITas the one handler that always runs -- normal end, error, or a trapped signal that callsexit. Cleanup belongs there, not scattered after every command.
- Registering the trap after acquiring the resource. If you run
tmp=$(mktemp)and only then calltrap 'rm -f "$tmp"' EXIT, a signal delivered in the gap leaves a temp file behind. Register the handler first, or make creation and registration a single indivisible step, so there is never a live resource without a trap watching it.
- Using double quotes when the variable is not set yet.
trap "rm -f $tmp" EXITexpands$tmpat the moment the trap is defined -- often to an empty string -- and bakes that in. Use single quotes,trap 'rm -f "$tmp"' EXIT, so$tmpis read when the trap fires and reflects its final value.
- Trying to trap KILL or STOP.
SIGKILL(9) andSIGSTOP(19) cannot be caught, blocked, or ignored -- the kernel acts on them directly. Atrap ... KILLis silently useless. Design cleanup around the signals you can catch (INT,TERM,HUP) and accept thatkill -9will always be able to leave a mess.
- Clobbering the exit status inside the handler. Any command in an
EXIThandler overwrites$?, so a naiveexitat the end of the trap returns the handler's status, not the script's. Capture it first: makerc=$?the very first line of the handler andexit "$rc"the last if you need to preserve the original code.
- Not re-raising a trapped signal correctly. A handler that catches
INTand simply returns lets the script continue as if nothing happened, and reports success. If you mean to abort, exit with128 + signal(130 forINT, 143 forTERM) so callers and shells that inspect the status can tell the process was interrupted.
- Expecting the ERR trap to fire inside functions without errtrace. An
ERRtrap is not inherited by shell functions, command substitutions, or subshells unlessset -E(errtrace) is active. Without it, afalseinside a function triggers nothing. PairERRtraps withset -eEso the trap follows execution into every function.
- Silently overwriting an existing trap. A second
trap 'handler2' EXITreplaces the first rather than adding to it; the earlier cleanup is simply lost. When code paths each need cleanup, register one handler that does everything, or read the current trap withtrap -p EXITand append to it deliberately.
- Writing cleanup that can fail or run twice. A handler that assumes the resource still exists will error on a second pass or when setup never finished. Guard every step (
[ -d "$dir" ] && rm -rf "$dir"), make the handler idempotent, and never let a failure in cleanup mask the real error that triggered the exit.
Best Practices
- Register the cleanup trap before you create the thing it cleans up. Set
trap 'cleanup' EXITat the top, then acquire resources. This closes the window where a signal can leave an orphan the handler never learns about, and keeps the invariant "if it exists, a trap is watching it."
- Single-quote the trap command so it is evaluated when the signal fires. Write
trap 'rm -f "$tmp"' EXIT, not double quotes, so variables read their final values at fire time rather than being frozen at the moment the trap was set.
- Put all cleanup on EXIT and reserve INT/TERM for messaging. Let
EXITdo the actual teardown; usetrap '...; exit 130' INT TERMonly to print an aborting message and exit with the right status, which then re-triggers the singleEXITcleanup.
- Capture the exit status as the handler's first act. Begin an
EXIThandler withrc=$?before running any command, and end withexit "$rc"when the original status must survive, so cleanup never silently turns a failure into a success.
- Make every handler idempotent and defensively guarded. Check that a resource exists before removing it (
[ -d "$d" ] && rm -rf "$d") so the handler is safe to run when setup only half-completed and safe to run more than once.
- Pair ERR traps with
set -eEfor diagnostics. Enable errtrace so anERRtrap follows execution into functions and subshells, and use it to log$BASH_COMMANDand the failing line -- turning a bare non-zero exit into an actionable message.
- Block signals around critical sections of cleanup. Wrap the parts that must not be interrupted with
trap '' INT TERMso a second Ctrl-C cannot halt a half-finishedrm -rf, then restore or exit; this prevents a partly-deleted workspace.
- Re-raise trapped signals with 128 plus the signal number. Exit 130 after
INTand 143 afterTERMso wrappers, CI systems, and interactive shells can distinguish "interrupted" from a clean exit and react accordingly.
Practice Exercises
- Guarded temp workspace. Write a script that creates a working directory with
mktemp -d, registers anEXITtrap that removes it only when the variable is non-empty and the directory exists, and writes one file inside it. Prove the directory is gone after the script ends, on both a clean exit and a forcedexit 1.
- Interrupt-safe copy. Write a script that copies a large file to a temporary name and renames it into place only on success. Trap
INTandTERMto remove the partial temporary file and exit 130, so an interrupted run never leaves a truncated destination. Trigger it with a self-sentkill -TERM $$to demonstrate.
- Status-preserving cleanup. Write an
EXIThandler that capturesrc=$?on its first line, printsexiting with status <rc>, performs cleanup, and finallyexit "$rc". Run the script so its last real command fails and confirm the reported status matches the failing command, not the cleanup.
- ERR-trap diagnostics. Write a script with
set -eEand anERRtrap that prints the failing command via$BASH_COMMAND. Put the failing command inside a function and show that the trap fires with errtrace enabled and prints nothing when you removeset -E, documenting the difference in a comment.