Traps and temporary files
Quick answer
Scripts often need private scratch space. Use mktemp to create it and an EXIT trap to remove only files the script owns.
Prepare the practice environment
Run python3 lab-fixtures/shell-scripting/setup.py as an ordinary user from the extracted package root in a disposable Linux environment. Enter the printed directory, check pwd, then run export LC_ALL=C; umask 077; set -o pipefail. Use a fresh fixture for each example. Save the code as example.sh inside that directory and run bash --noprofile --norc -o pipefail example.sh rather than sourcing it. Stop if a command fails unexpectedly. All output paths must be new. The source of check-report.sh is in the fixture JSON. Outputs below are not commands.
How it works
mktemp -d creates a unique directory and reports its path. This lab uses a relative template within the private working directory. Check success before registering cleanup. trap cleanup EXIT runs the function when Bash exits normally or through many ordinary error exits. It cannot guarantee cleanup after SIGKILL, power loss or every crash. Capture $? first inside cleanup, disable the EXIT trap before explicit exit, and preserve the original status unless cleanup itself fails after success. Remove only known files and use rmdir for the empty directory; never recursively delete an unchecked variable.
If the work fails with status 7 and cleanup succeeds, the final status should still be 7 so the caller can detect the failure. If the work succeeds but cleanup fails, the example reports a cleanup failure instead of silently claiming full success. Restrict cleanup to the private fixture and its known file names; if an unexpected entry prevents rmdir, stop and investigate rather than expanding the deletion scope. A trap is useful for ordinary exits, not a guarantee of recovery from every interruption.
Try the examples
work=$(mktemp -d ./scratch.XXXXXXXX) || exit 1stat -c '%a' "$work"rmdir -- "$work"The mode is 700 in the tested environment. Only the newly created empty directory is removed.
Expected stdout:
700(trap 'printf "cleanup called\\n"' EXIT; printf 'work done\n')The handler runs when the subshell exits.
Expected stdout:
work donecleanup called( work=$(mktemp -d ./scratch.XXXXXXXX) || exit 1 cleanup() { rc=$? trap - EXIT if [[ $work == ./scratch.???????? && -d $work && ! -L $work ]]; then if ! rm -f -- "$work/report.txt" || ! rmdir -- "$work"; then printf 'cleanup failed\n' >&2 (( rc == 0 )) && rc=1 fi else printf 'unexpected scratch path\n' >&2 (( rc == 0 )) && rc=1 fi exit "$rc" } trap cleanup EXIT printf 'ready\n' > "$work/report.txt" || exit 1 cat "$work/report.txt") && printf 'finished\n'The cleanup is scoped to the trusted fixture and known file. The path pattern is not a general defense against concurrent malicious modification.
Expected stdout:
readyfinishedCommon mistakes
Never use a predictable shared temporary filename or rm -rf on a variable of uncertain origin. This example assumes a private working directory and no hostile concurrent writers.
Practice
Run the cleanup example, inspect the directory for leftover scratch entries, then insert exit 7 after creating the report and confirm cleanup still happens and status 7 survives.
Related references
Study: trap, mktemp. These are reference names, not deployed links.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Traps and temporary files — Knowledge Check
Apply the lesson concepts to the controlled shell fixture.
Why use mktemp -d?
What should cleanup capture first?
Which termination cannot an EXIT trap guarantee handling?
Which cleanup approach suits this lab?