trap: Cleanup, Signals and Exit Status
A script that creates temporary files, starts a background process, takes a lock or puts a service in maintenance
mode has made a promise: to undo it. trap is how Bash keeps that promise on every exit path, whether the script
succeeds, fails under set -e, or is stopped with Ctrl+C or kill. The Linux lesson showed
the basic trap … EXIT; this lesson makes it robust.
A cleanup function that keeps the exit status
Put cleanup in a function, register it once for EXIT, and make sure it does not change the status the caller sees:
cat > job.sh <<'SCRIPT'
#!/usr/bin/env bash
set -euo pipefail
workdir=$(mktemp -d)
cleanup() {
local rc=$? # the status the script is exiting with
rm -rf -- "$workdir"
echo "cleanup: removed workdir (exit status $rc)" >&2
exit "$rc"
}
trap cleanup EXIT
echo "step 1" > "$workdir/out"
[ "${1:-}" = fail ] && { echo "simulated failure" >&2; exit 3; }
echo "job finished"
SCRIPT
bash job.sh; echo "-> status $?"
bash job.sh fail; echo "-> status $?"
ls /tmp | grep -c '^tmp\.' || truejob finished
cleanup: removed workdir (exit status 0)
-> status 0
simulated failure
cleanup: removed workdir (exit status 3)
-> status 3
0
Three details matter:
local rc=$?must be the first line: any command, evenrm, overwrites$?.exit "$rc"at the end makes the status explicit, so later edits to the function (an extra command, an earlyreturn) cannot turn a failed job into one that looks successful.- The last line of the session checks that no
tmp.*directory was left behind in either run.
Signals: Ctrl+C and kill
An EXIT trap also runs when the script is stopped by a signal such as SIGTERM (what kill, systemctl stop,
Docker and Kubernetes send first). Here the script kills itself to show it:
cat > stop.sh <<'SCRIPT'
trap 'echo "EXIT trap ran"' EXIT
echo "working"
kill -TERM $
echo "never printed"
SCRIPT
bash stop.sh; echo "-> status $?"working
EXIT trap ran
Terminated
-> status 143
The status 143 is 128 + 15 (SIGTERM). The Terminated line comes from the outer shell reporting how its child died.
Two habits make signal handling predictable across shells and versions:
cleanup() { local rc=$?; rm -rf -- "$workdir"; exit "$rc"; }
trap cleanup EXIT
trap 'exit 130' INT # Ctrl+C: exit, which runs the EXIT trap, with the conventional status
trap 'exit 143' TERM # kill / docker stop / Kubernetes: sameTurning each signal into an exit with the matching status means there is exactly one cleanup path (the EXIT trap)
and the caller still sees "killed by a signal". SIGKILL (kill -9) cannot be trapped at all: nothing runs, which is
one reason to keep temporary state somewhere a later run can find and remove it.
Note: In a container, your script is often PID 1. The kernel does not apply default signal actions to PID 1, so a script without a
TERMtrap ignoresdocker stopuntil the 10-second timeout ends inSIGKILL. Atrap 'exit 143' TERM, orexec-ing the real program at the end of an entrypoint script, fixes it.
ERR traps and functions
An ERR trap is handy for reporting where a script failed. By default it is not inherited by functions, so a
failure inside a function exits silently. set -E (errtrace) fixes that:
cat > err.sh <<'SCRIPT'
set -euo pipefail
trap 'echo "failed at line $LINENO: $BASH_COMMAND" >&2' ERR
load() { grep -q "^port=" app.conf; }
load
SCRIPT
cat > err2.sh <<'SCRIPT'
set -Eeuo pipefail
trap 'echo "failed at line $LINENO: $BASH_COMMAND" >&2' ERR
load() { grep -q "^port=" app.conf; }
load
SCRIPT
echo "debug=true" > app.conf
bash err.sh; echo "-> status $?"
bash err2.sh; echo "-> status $?"-> status 1
failed at line 3: grep -q "^port=" app.conf
-> status 1
$BASH_COMMAND is the command that failed and $LINENO its line. For a full call stack, walk FUNCNAME,
BASH_SOURCE and BASH_LINENO in the trap.
One trap per signal
A second trap … EXIT replaces the first; it does not add to it. That is a classic bug when a script grows:
someone adds "stop the test server" as a new EXIT trap, and the temporary directory is no longer removed. Keep a
single cleanup function and let it undo everything that has been set up so far:
cat > grow.sh <<'SCRIPT'
set -euo pipefail
workdir="" server_pid=""
cleanup() {
local rc=$?
if [ -n "$server_pid" ]; then kill "$server_pid" 2>/dev/null || true; echo "stopped server"; fi
if [ -n "$workdir" ]; then rm -rf -- "$workdir"; echo "removed workdir"; fi
exit "$rc"
}
trap cleanup EXIT
workdir=$(mktemp -d)
python3 -m http.server 8000 --bind 127.0.0.1 >"$workdir/server.log" 2>&1 &
server_pid=$! # a local test server
for _ in $(seq 50); do curl -s -o /dev/null 127.0.0.1:8000/ && break; sleep 0.1; done
echo "server ready, running tests"
false # a test fails
SCRIPT
bash grow.sh; echo "-> status $?"server ready, running tests
stopped server
removed workdir
-> status 1
The wait loop matters for more than speed. A background job starts life as a copy of the shell, traps included,
until it execs the real program; kill it in that instant and the copy runs your EXIT trap too (here it would
remove the work directory a second time). Waiting until the server answers, with a bounded loop, removes the race.
Each resource is recorded in a variable when it is created, and the cleanup function only undoes what exists. A
failure halfway through setup therefore cleans up exactly the part that was done. trap -p prints the traps that are
currently set, which helps when debugging a script that sources other files.
Test yourself
Why must local rc=$? be the first line of the cleanup function?
localmust always come first in Bash- Every command overwrites
$?, so it must be saved before anything else runs - Otherwise the trap does not fire
$?is only defined on line 1
A script sets trap cleanup_tmp EXIT and later trap stop_server EXIT. What runs at exit?
- Both, in order
- Both, in reverse order
- Only
stop_server: the second trap replaced the first - Neither
What does set -E change?
- Exits on unset variables
- Makes the ERR trap fire inside functions, subshells and command substitutions too
- Enables extended globbing
- Prints each command before running it