Cleaning Up Temporary Files on Exit
Scripts create temporary files and directories all the time: a place to collect intermediate results, a scratch copy of a file being edited, a download that is checked before it is moved into place. Lesson 113 showed how to create them safely with mktemp. This lesson covers the other half: making sure they are removed again, no matter how the script ends. The tool for that is an EXIT trap (lesson 123), and most of the details are about using it correctly.
Why "rm at the End" Is Not Enough
The obvious approach removes the file on the last line:
tmp=$(mktemp)
echo "created $tmp"
ls /nonexistent > "$tmp" 2>&1 || exit 1
rm -f -- "$tmp"
created /tmp/tmp.fOPFLzFgRa
The script ended with status 1, and a check afterwards confirmed that /tmp/tmp.fOPFLzFgRa was still there. Every exit before the last line, every failure that stops a set -e script, and every Ctrl+C skips the rm. Run often enough, such a script fills /tmp with forgotten files, and if the files contain data (a database dump, a decrypted secret), leaving them behind is a security problem as well as clutter.
The Basic Pattern
Register the cleanup right after creating the file:
tmp=$(mktemp)
trap 'rm -f -- "$tmp"' EXIT
ls /nonexistent > "$tmp" 2>&1 || exit 1
echo "not reached"
The script still ended with status 1, but this time the file was gone. The EXIT trap runs on every normal way out: the end of the script, an exit anywhere, and a stop caused by set -e. In Bash it also runs when SIGINT or SIGTERM ends the script (lesson 123).
The parts of the trap command each have a purpose:
- Single quotes delay the expansion of
$tmpuntil the trap runs. The trap uses whatever value the variable has at exit time. rm -fdoes not complain or fail if the file is already gone, for example because the script moved it to its final location.--ends the option list, so a path that begins with-cannot be mistaken for an option.- Double quotes around
$tmpkeep a path with spaces in one piece (lesson 55).
A Temporary Directory for Several Files
When a script needs more than one temporary file, create one temporary directory and put everything inside it. A single rm -rf removes it all, and there is only one path to keep track of:
workdir=$(mktemp -d)
trap 'rm -rf -- "$workdir"' EXIT
touch "$workdir/a.txt" "$workdir/b.txt"
mkdir "$workdir/sub"
touch "$workdir/sub/c.txt"
After the script ended, the directory and everything in it, including the subdirectory, were gone. mktemp -d creates the directory with mode 700, so other users cannot look inside while the script runs (lesson 113).
Order and Unset Variables
The trap refers to a variable, so it matters what that variable holds when the trap runs. If the trap is set first and the script exits before the variable is assigned, set -u turns the cleanup itself into an error:
set -u
trap 'rm -f -- "$tmp"' EXIT
exit 1
tmp=$(mktemp)
order.sh: line 1: tmp: unbound variable
There are three clean solutions:
- Set the trap immediately after
mktemp, as in the basic pattern. There is no moment where the trap exists without the variable. - Give the variable an empty value first and test it in the cleanup:
tmp=followed bytrap '[[ -n $tmp ]] && rm -f -- "$tmp"' EXIT. - Use a default in the expansion:
trap 'rm -f -- "${tmp-}"' EXIT. With an empty argument,rm -fdoes nothing and succeeds.
The second form ends with a test that is false when nothing was created. That does not change the script's exit status: a script whose EXIT trap ended with a failed [[ -n $tmp ]] still exited with 0. The exit status changes only if the trap itself calls exit.
When mktemp itself fails, there is nothing to clean up, and the script should stop with a clear message before relying on the variable:
tmp=$(mktemp -p /nonexistent) || { echo "cannot create temp file" >&2; exit 1; }
trap 'rm -f -- "$tmp"' EXIT
mktemp: failed to create file via template '/nonexistent/tmp.XXXXXXXXXX': No such file or directory
cannot create temp file
A Cleanup Function
Once there is more than one thing to clean up, a function is easier to read and maintain than a long trap string. A good cleanup function saves the exit status in its first line and passes it on at the end:
cleanup() {
local rc=$?
rm -f -- "$tmp"
echo "cleanup done, exiting with $rc" >&2
exit "$rc"
}
tmp=$(mktemp)
trap cleanup EXIT
false
exit 4
cleanup done, exiting with 4
The script ended with status 4. local rc=$? must be the very first command: any command before it, even an echo, would replace $?. Ending with exit "$rc" (or return "$rc", which also kept status 5 in a separate test) makes the final status explicit, so nothing inside the function can change it by accident.
Keep set -e Out of the Cleanup Path
A cleanup function runs under the same options as the rest of the script. Under set -e, a failing command in the cleanup stops the cleanup halfway:
set -e
cleanup() {
rm -- "$tmp.missing"
echo "second step"
}
tmp=$(mktemp)
trap cleanup EXIT
echo "body done"
body done
rm: cannot remove '/tmp/tmp.YaQ4GDZgzk.missing': No such file or directory
Three things went wrong at once: second step never ran, the real temporary file $tmp was not removed, and a script that had finished its work successfully exited with status 1. Write cleanup commands so they cannot fail: rm -f instead of rm, kill ... 2>/dev/null for processes that may already have ended, and tests such as [[ -n $var ]] before acting. With rm -f -- "$tmp.missing" "$tmp" the same script printed second step and exited with 0. In a longer cleanup function, set +e as its second line (after saving $?) is another option.
Making Signals Run the Cleanup Everywhere
Bash runs the EXIT trap when SIGINT or SIGTERM ends a script, but not every shell does. A Dash script with only an EXIT trap, sent SIGTERM while waiting, ended with status 143 and left its temporary file behind. Adding explicit signal traps that call exit fixes this, because exit always runs the EXIT trap:
tmp=$(mktemp)
trap 'rm -f -- "$tmp"; echo "dash cleanup ran"' EXIT
trap 'exit 143' TERM
trap 'exit 130' INT
sleep 5 &
wait
dash cleanup ran
The status was 143 and the file was removed. These extra traps also make the intent explicit in Bash, and they give the script a place to print a message such as "interrupted".
The cleanup still runs only once. In a Bash test with an EXIT trap and trap 'exit 130' INT, sending SIGINT printed cleanup called a single time and ended with status 130: the INT trap called exit, and exit ran the EXIT trap. Putting the cleanup command itself into the INT and TERM traps as well would run it twice, which is why the signal traps should only call exit.
Things Cleanup Cannot Cover
SIGKILL.
kill -9ends the process without running any trap (lesson 123). Keep temporary files in the system temporary directory, where the operating system or a periodic job can remove leftovers, rather than in the user's working folder.exec.execreplaces the shell with another program, so the shell never exits and its EXIT trap never runs:tmp=$(mktemp) trap 'rm -f -- "$tmp"; echo "trap ran"' EXIT exec echo "replaced by echo"replaced by echoThe trap did not run and the file stayed behind. Remove temporary files before an
exec, or run the program normally and let the script exit afterwards.Subshells. A subshell does not run the parent's EXIT trap. When a subshell creates its own temporary file, give it its own trap inside the parentheses; in the test,
( t=$(mktemp); trap 'rm -f -- "$t"' EXIT; ... )removed the file when the subshell ended.
Stopping Background Processes
Background processes are also resources that a script should release. A process started with & keeps running after the script ends unless something stops it:
sleep 30 &
echo "main work done, no cleanup"
A check after the script ended showed the sleep process still running, orphaned. The cleanup function can stop it:
helper_pid=
cleanup() {
if [[ -n $helper_pid ]]; then
kill "$helper_pid" 2>/dev/null
wait "$helper_pid" 2>/dev/null
echo "helper $helper_pid stopped"
fi
}
trap cleanup EXIT
sleep 30 &
helper_pid=$!
echo "main work done"
main work done
helper 660 stopped
Afterwards the process was gone. $! is the process ID of the last background command (lesson 139). wait collects the process after kill, so Bash does not later print a "Terminated" job message. Both commands send their errors to /dev/null because the helper may already have finished on its own.
Keeping Files for Debugging
When a script fails, its intermediate files are often the best evidence of what went wrong. An environment variable can switch the cleanup off on request:
workdir=$(mktemp -d)
cleanup() {
local rc=$?
if [[ -n ${KEEP_TMP-} ]]; then
echo "keeping $workdir for inspection" >&2
else
rm -rf -- "$workdir"
fi
return "$rc"
}
trap cleanup EXIT
echo data > "$workdir/out.txt"
A normal run removed the directory. Run as KEEP_TMP=1 ./script.sh, it printed:
keeping /tmp/tmp.XXXXXXXXXX for inspection
and the directory was still there afterwards (the random part of the name differs on every run). ${KEEP_TMP-} keeps the test safe under set -u.
A Complete Example
This script merges several text files into one sorted list without duplicates. It works inside a temporary directory and only replaces the output file at the very end, so an error or an interruption never leaves a half-written output file or stray temporary files:
#!/usr/bin/env bash
# merge-lists.sh OUTPUT INPUT...: merge text files into OUTPUT, sorted and without duplicates
set -euo pipefail
prog=${0##*/}
workdir=
cleanup() {
local rc=$?
if [[ -n $workdir ]]; then
rm -rf -- "$workdir"
fi
exit "$rc"
}
trap cleanup EXIT
trap 'echo "$prog: interrupted" >&2; exit 130' INT
trap 'echo "$prog: terminated" >&2; exit 143' TERM
if (( $# < 2 )); then
echo "usage: $prog OUTPUT INPUT..." >&2
exit 2
fi
out=$1
shift
workdir=$(mktemp -d)
echo "$workdir" > .last_workdir # recorded only so the test can check it
# Step 1: copy every input, normalizing line endings
n=0
for f in "$@"; do
n=$((n + 1))
tr -d '\r' < "$f" > "$workdir/part$n"
done
# Step 2: merge (DELAY simulates a slow step for testing)
sleep "${DELAY:-0}"
sort -u "$workdir"/part* > "$workdir/merged"
# Step 3: replace OUTPUT in one step
mv -- "$workdir/merged" "$out"
echo "$prog: wrote $(wc -l < "$out") unique lines to $out"
a.txt held apple, banana and cherry; b.txt held banana, date and apple with Windows (CRLF) line endings. The .last_workdir line exists only so the test could check after each run that the work directory was removed:
./merge-lists.sh; echo "status $?"
./merge-lists.sh all.txt a.txt b.txt; echo "status $?"
./merge-lists.sh all2.txt a.txt missing.txt; echo "status $?"
DELAY=5 ./merge-lists.sh all3.txt a.txt b.txt & p=$!
sleep 1; kill -TERM "$p"; wait "$p"; echo "status $?"
usage: merge-lists.sh OUTPUT INPUT...
status 2
merge-lists.sh: wrote 4 unique lines to all.txt
status 0
./merge-lists.sh: line 32: missing.txt: No such file or directory
status 1
merge-lists.sh: terminated
status 143
all.txt contained apple, banana, cherry and date. After the failed run and the terminated run, neither all2.txt nor all3.txt existed, and in all three runs that created a work directory, it was removed.
How it works:
workdir=is set before the trap, andcleanupchecks it, so an exit beforemktemp(the usage error) does not try to remove anything.- The failed redirection
< "$f"for the missing file stopped the script underset -e. Without a trap,part1would have been left behind in/tmp. - SIGTERM arrived during
sleep 5. As lesson 123 explained, Bash handled it whensleepfinished; the TERM trap printed its message and calledexit 143, which rancleanup, which kept the status 143. - The output file is written only by the final
mv. Before that line, the oldOUTPUT(if any) is untouched; after it, the new file is complete. Becausesortcreatedmergednormally rather than throughmktemp, the result had the usual permissions (-rw-r--r--here) rather than the600mode of a file made bymktemp(lesson 113). Moving from/tmpto another file system is a copy rather than an atomic rename; lesson 113 covers creating the temporary file next to the target when that matters.
The examples were run with Bash 5.2.21, Dash 0.5.12 and GNU coreutils 9.4 on Ubuntu 24.04. Temporary file names and process IDs differ on every run.