brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: trap EXIT cleans up your temp files, even when the script dies

Shell
~/tips/tip-shell-trap-exit-mktemp

trap 'rm -rf "$tmp"' EXIT

Runs a cleanup command whenever the script exits, including after an error.

Scripts that make temp files tend to leave them behind. The cleanup line sits at the bottom and never gets reached when something fails earlier.

Bash runs the command from trap ... EXIT when the shell exits, whatever the reason: normal end, exit 1, or an error under set -e. Combine it with mktemp -d, which makes a private directory with a random name.

tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT

curl -fsSL "$url" -o "$tmp/data.json"
jq . "$tmp/data.json"

Write the trap right after the mktemp, so there is no gap where a failure leaves the directory behind. Use single quotes so $tmp is expanded when the trap runs, not when you define it.

Caveats. A SIGKILL cannot be trapped, so kill -9 still leaves the mess. And a script can only have one EXIT trap per shell: setting a second one replaces the first. If you need several cleanups, put them in one function and trap that.

I find it a calm pattern: every script that needs scratch space gets the same two lines at the top, and I stop thinking about leftovers in /tmp.

Further reading: Bash manual: Bourne Shell Builtins (trap), GNU coreutils: mktemp, On this site: ${var:?} stops a script before an empty variable eats your files, On this site: set -o pipefail makes a pipeline fail when any part of it fails

More Shell tips zmv -n '(*).log' '$1.txt' zoxide query -ls project f=$(mktemp --suffix=.json) shopt globskipdots echo $EPOCHSECONDS All Shell tips (78) All topics

Link