Robust Scripts
Cleanup Traps
Always Remove Temporary Files
Temporary files should be cleaned up even when a script exits early. An EXIT trap gives cleanup one reliable place to live.
Program
Play the script to watch a temporary directory become a report path, then follow the EXIT trap into cleanup.
trap_cleanup.sh
Replay: real traced execution (multi-file project)
#!/usr/bin/env bash
tmp="$(mktemp -d)"
cleanup() {
rm -rf "$tmp"
}
trap cleanup EXIT
file="$tmp/report.txt"
printf 'ok\n' > "$file"
echo "${file##*/}"
tmp ← /tmp/tmp.dir
3tmp="$(mktemp -d)"4cleanup() {values this step/tmp/tmp.dirtmptrap ← cleanup EXIT
6}7trap cleanup EXIT8file="$tmp/report.txt"values this stepcleanup EXITtrap/tmp/tmp.dirtmpfile ← /tmp/tmp.dir/report.txt
7trap cleanup EXIT8file="$tmp/report.txt"9printf 'ok\n' > "$file"values this step/tmp/tmp.dir/report.txtfile/tmp/tmp.dirtmpfile contents ← ok
8file="$tmp/report.txt"9printf 'ok\n' > "$file"10echo "${file##*/}"values this stepokfile contents/tmp/tmp.dir/report.txtfileecho "${file##*/}"
9printf 'ok\n' > "$file"10echo "${file##*/}"outputreport.txtvalues this step/tmp/tmp.dir/report.txtfileEXIT trap ← fires cleanup
3tmp="$(mktemp -d)"4cleanup() {5 rm -rf "$tmp"values this stepfires cleanupEXIT traptmp ← removed
4cleanup() {5 rm -rf "$tmp"6}values this step/tmp/tmp.dir → removedtmp
Follow the Trace
mktemp -dcreates a temporary directory; the trace normalizes it as/tmp/tmp.dir.trap cleanup EXITregisters cleanup for the end of the script.filebecomes/tmp/tmp.dir/report.txt.- The script writes
okto the file and prints its basename,report.txt. - On exit, the trap runs cleanup and the temporary directory is removed.
| trace point | value |
| --- | --- |
| normalized temp dir |
/tmp/tmp.dir| | report file |/tmp/tmp.dir/report.txt| | file contents |ok| | stdout |report.txt| | after EXIT trap | temp dir removed |
trap
`trap cleanup EXIT` registers a cleanup command for the shell to run later.
EXIT
The `EXIT` trap runs when the script ends normally and after many failures.
temporary directory
`mktemp -d` creates an isolated directory for short-lived files.
Exercise: trap_cleanup.sh
Reproduce report.txt, then trace which path is cleaned up by the EXIT trap.