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##*/}"
  1. tmp ← /tmp/tmp.dir

    3tmp="$(mktemp -d)"4cleanup() {
    values this step/tmp/tmp.dirtmp
  2. trap ← cleanup EXIT

    6}7trap cleanup EXIT8file="$tmp/report.txt"
    values this stepcleanup EXITtrap/tmp/tmp.dirtmp
  3. file ← /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.dirtmp
  4. file contents ← ok

    8file="$tmp/report.txt"9printf 'ok\n' > "$file"10echo "${file##*/}"
    values this stepokfile contents/tmp/tmp.dir/report.txtfile
  5. echo "${file##*/}"

    9printf 'ok\n' > "$file"10echo "${file##*/}"
    outputreport.txt
    values this step/tmp/tmp.dir/report.txtfile
  6. EXIT trap ← fires cleanup

    3tmp="$(mktemp -d)"4cleanup() {5  rm -rf "$tmp"
    values this stepfires cleanupEXIT trap
  7. tmp ← removed

    4cleanup() {5  rm -rf "$tmp"6}
    values this step/tmp/tmp.dir removedtmp

Follow the Trace

  1. mktemp -d creates a temporary directory; the trace normalizes it as /tmp/tmp.dir.
  2. trap cleanup EXIT registers cleanup for the end of the script.
  3. file becomes /tmp/tmp.dir/report.txt.
  4. The script writes ok to the file and prints its basename, report.txt.
  5. 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.