Traps and cleanup
Run cleanup code however a script ends with trap on EXIT and signals, create temp files safely with mktemp, and know what a trap cannot catch.
Strict mode - set -e, -u and pipefailFunctions, arguments and scopeExit status and && / || lists
Traps and cleanup
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- `trap 'commands' EXIT` runs the commands when the script ends, whether it finished, hit an error under `set -e`, or was stopped by a catchable signal.
- A trap can name signals such as `INT` and `TERM`. After a signal the script exits with 128 plus the signal number, so 143 for `TERM`.
- `SIGKILL` cannot be trapped, so a script killed with `kill -9` leaves its temp files behind.
- Put trap commands in single quotes, or call a function, so variables are expanded when the trap fires, not when it is set.
- `mktemp` creates a uniquely named temp file or directory. Combine it with an `EXIT` trap that removes it.
Leaving a mess behind
A script that creates a temporary file has one rule to follow: remove it when you’re done. The tempting way is a line at the bottom, rm -f "$tmp". The trouble is that “the bottom” isn’t the only way a script ends. It may hit an error under set -e and exit early. It may be stopped with Ctrl-C or killed by a supervisor. In every one of those cases the last line never runs, and the temp file stays.
A trap is the shell’s answer. It registers commands that Bash runs when a certain event happens. The most useful event is EXIT, a pseudo-signal that fires whenever the shell is about to terminate, for nearly any reason.
logsum v8: a temp file that cleans up after itself
#!/usr/bin/env bash
# logsum v8: a temp file that is always cleaned up
set -euo pipefail
tmp=$(mktemp "${TMPDIR:-/tmp}/logsum.XXXXXX")
cleanup() {
rm -f "$tmp"
echo "cleanup: removed $(basename "$tmp")" >&2
}
trap cleanup EXIT
awk '{ print $6 }' "${1:-logs/access.log}" | sort | uniq -c | sort -rn > "$tmp"
head -n 3 "$tmp"
[[ ${FAIL:-0} -eq 1 ]] && { echo "simulated failure" >&2; exit 4; }
[[ ${SLOW:-0} -eq 1 ]] && sleep 5
exit 0
mktemp creates a file with a unique name, replacing the XXXXXX with random characters, so two runs can’t collide. The trap cleanup EXIT line registers the cleanup function. The FAIL and SLOW variables exist so I could trigger an error exit and a long-running script.
I pointed TMPDIR at a scratch folder so I could count what was left over. Normal run and failing run:
$ ./logsum; echo "status: $?"; ls "$TMPDIR" | wc -l
24 /about
23 /static/app.js
23 /
cleanup: removed logsum.ova8EW
status: 0
0
$ FAIL=1 ./logsum; echo "status: $?"; ls "$TMPDIR" | wc -l
24 /about
23 /static/app.js
23 /
simulated failure
cleanup: removed logsum.mIbS1X
status: 4
0
The name after “removed” is the real random name from that run, and yours will differ. In both runs the file was removed and the directory was left empty, and the failing run kept its exit status 4. A trap doesn’t change the status the script exits with.
Signals
An EXIT trap also runs when a catchable signal ends the script. I started a slow copy in the background and sent SIGTERM:
$ SLOW=1 ./logsum & pid=$!; sleep 1; kill -TERM $pid; wait $pid; echo "status after TERM: $?"; ls "$TMPDIR" | wc -l
24 /about
23 /static/app.js
23 /
cleanup: removed logsum.uZWTM6
status after TERM: 143
0
The cleanup ran, and the status was 143, which is 128 plus signal number 15. Shells report death-by-signal that way. I meant to test Ctrl-C (INT) the same way, but a non-interactive shell starts background jobs with SIGINT ignored, so my kill -INT did nothing and the script ran to the end. I couldn’t test Ctrl-C at a real terminal here. You can also name signals explicitly, as in trap cleanup EXIT INT TERM, though EXIT alone covers the cases I checked.
What a trap can’t catch
SIGKILL can’t be trapped, because the kernel ends the process without giving it a chance to run anything:
$ SLOW=1 ./logsum & pid=$!; sleep 1; kill -KILL $pid; wait $pid; echo "status after KILL: $?"; ls "$TMPDIR" | wc -l
bash: 26793 Killed: 9 SLOW=1 ./logsum
status after KILL: 137
1
No cleanup line, status 137 (128 plus 9), and one temp file left behind. So kill -9 is a last resort for a stuck script, and any script that cares should use TERM first. Likewise, a power cut or a crash leaves temp files. The safe temporary files lesson covers how to cope with that.
Single quotes in a trap string
The command string you give trap is run later, so it matters when variables are expanded. This script showed both ways:
$ ./order.sh
single quotes: name is second
trap -- 'echo '\''double quotes: name was '\''first' EXIT
trap -- 'echo "single quotes: name is $name"' SIGUSR1
double quotes: name was first
With double quotes, $name was expanded when the trap was set, so the output was frozen at first, even though name became second later. With single quotes the expansion waited until the signal arrived and used second. That’s why ShellCheck flags the double-quoted version as SC2064, “Use single quotes, otherwise this expands now rather than when signalled.” trap -p prints what is registered. The simplest rule is to make the trap command a function name, as in trap cleanup EXIT, and let the function read the variables at run time. ShellCheck also reports cleanup in logsum as “never invoked” (SC2329, info level), a false positive because the trap calls it indirectly.
The ERR trap
trap '...' ERR fires when a command fails, which gives you a place to print context that a bare set -e exit lacks:
$ ./errtrap.sh; echo "status: $?"
ERR trap: line 6, status 1
EXIT trap: status 1
status: 1
The script used set -eE and the line number came from $LINENO. The -E is documented to make the ERR trap apply inside functions too, though I didn’t test a function case. Both traps fired in order, ERR first and then EXIT.
About the video
Nick Janetakis’s “Using trap to Run a Command after Your Shell Script Exits” is 15 minutes 27 seconds and was published in May 2023. The description says you can use trap to delete temp files, write log entries, or do anything on exit, and its timestamps list “A few use cases” at 0:25 and “Running the script without tra[p]” at 1:41. I couldn’t read a transcript, and I only saw the first two chapter titles in the text I had. It is in English. I found no better embeddable trap video, so there is no runner-up.
Where this fits
Traps and temp files lean on a fact I’ve mentioned several times: background jobs and pipelines run in child shells. The next lesson explains that properly, with subshells and process substitution.
Check yourself
Why is `trap cleanup EXIT` better than putting `rm -f "$tmp"` at the end of the script?
The last line runs only if the script reaches it. The trap also runs after an error under `set -e`, an `exit` in the middle, or a `TERM` signal.
What exit status does a script report after it is stopped with `kill -TERM`, and why?
143, which is 128 plus signal 15. Shells report death-by-signal as 128 plus the signal number, which is why the trap can still run and the status shows what happened.
What can't a trap protect you from?
`SIGKILL` (`kill -9`) and a power loss. The process is destroyed with no chance to run code, so the temp file stays. I saw one file left after a `kill -KILL`.
What is the difference between `trap "echo $name" EXIT` and `trap 'echo $name' EXIT`?
Double quotes expand `$name` when the trap is set, so it prints the value at that moment. Single quotes defer expansion until the trap runs, so it prints the value at exit.
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.