Revision: 1 Last modified: 2026-12-04T18:15:21Z
This is a library. It is sourced, never executed. Mode rw-rw-r--. Bash only — see the shell contract
below.
It creates one per-run temp directory, points TMPDIR at it, and removes it on EXIT, INT, TERM and HUP.
It exists because of a measured leak class (TMP-LEAK-07): a script or test that calls mktemp -d many times —
often inside $(...), where a registration array is lost — and relies on trap … EXIT, leaks directories
whenever it is killed or a subshell hides the path. With this helper, every mktemp in the script and in its
children (including a child later killed by SIGKILL) allocates inside the one directory, so a single removal
reclaims all of it.
SIGKILL cannot be trapped: the run directory then survives — but it is one directory under the original
TMPDIR instead of hundreds. Removal uses safe_rm_rf (§11.4.287) on the ${TMP_RUN_DIR:?}-guarded path, with
TMPDIR restored first, because safe_rm_rf refuses to delete the temp root itself.
- Bash ≥ 4 (bash 5.3 is what the test suite runs on). A non-bash shell (dash, busybox
sh) gets a diagnostic on stderr and a return of1before any bash-only syntax is parsed — no run dir is created and nothing is chained, so sourcing it fromshcannot produce a parse error mid-file. mktemp,safe_rm_rf(sourced automatically fromsafe_rm.shbeside this file).- bash < 4 (no
$BASHPID, e.g. macOS/bin/bash3.2) isUNCONFIRMED:— there was no such bash on the development host; the missing-$BASHPIDpath was exercised only byunset BASHPID. There the signal is re-raised through a directsh -c 'kill -s SIG "$PPID"'child; if even that cannot kill the process, a diagnostic is printed and the process exits128+N, i.e. the behaviour difference is announced, never silent. Whether$(trap -p EXIT)shows the current shell's trap on bash 3.2 is alsoUNCONFIRMED:— if it does not, a caller EXIT trap installed before init is not chained there.
. "$REPO/scripts/lib/tmp_run_dir.sh"
tmp_run_dir_init "myscript" || exit 2 # sets and exports TMP_RUN_DIR, exports TMPDIR=$TMP_RUN_DIR
mktemp -d # lands inside $TMP_RUN_DIR
tmp_run_dir_cleanup # optional early removal (also runs from the traps)| Function | Returns | Effect |
|---|---|---|
| (sourcing in a non-bash shell) | 1 (or exit 1 when not sourceable) |
diagnostic on stderr; nothing created, nothing chained |
| (sourcing twice in one shell) | 0 |
the second source is a no-op, so the first run dir and its chained caller trap are not forgotten |
tmp_run_dir_init PREFIX |
0 |
TMP_RUN_DIR set and exported; TMPDIR exported as the run dir; EXIT/INT/TERM/HUP traps armed |
0 (again) |
idempotent — exactly one run dir per process | |
1 |
mktemp failed, or a relative TMPDIR that is not a directory. On that path the signal traps are removed and the previous EXIT trap is restored |
|
tmp_run_dir_cleanup |
0 |
the run dir is gone (TMPDIR restored to the caller's original value, or unset if it was unset) |
0 (also) |
nothing to do when TMP_RUN_DIR is empty |
- An EXIT trap that already exists in this shell when
tmp_run_dir_initruns is chained — ours first, then the caller's, with the original exit status visible to it and preserved afterwards. - INT/TERM/HUP traps are REPLACED, not chained.
- On INT/TERM/HUP the EXIT trap in force at that moment runs (in a subshell, so an
exitinside it cannot skip the re-raise) before the process re-raises the signal and dies by it. It does notexit 128+N, because bash only stops afor/whileloop on Ctrl-C when the foreground child died of SIGINT. - A script that installs its own EXIT trap after init must call
tmp_run_dir_cleanupfrom it.
- A subshell's
trap -pshows the parent's EXIT trap until the subshell sets a trap of its own. So the signal traps are installed before the EXIT trap is read, and the installing instance is recorded in_TMP_RUN_DIR_OWNER; both handlers refuse to act in any other shell instance. Without this, a subshell would chain — and later execute — a trap belonging to another shell. set -ecallers — the handlers switcherrexitoff for their own work and give the chained trap its exit status throughif (exit N); then …; else …; fi(a condition is exempt fromerrexit), so aset -ecaller still has its trap run on every non-zero exit and every signal.- A second signal during cleanup — further INT/TERM/HUP are ignored while the removal finishes
synchronously, then the chain runs once (the pending chain is taken here). The interrupted outer handler
never resumes because the process dies by the signal. A post-init caller trap interrupted by a second signal
may run twice (
S-8, tracked). - The run dir path is forgotten only after the removal finished, and the removal is retried three times, so a handler that interrupts mid-removal finds the path still set and finishes the job.
- A relative
TMPDIRis made absolute at init (or init fails loudly). A cleanup that cannot remove the run dir says so on stderr withsafe_rm_rf's refusal reason — it is never silent. - POSIX mode —
trap -pprints-for "no trap"; that is treated as no trap. - A foreign shell instance on the signal path sets
trap - EXIT INT TERM HUPfor itself and never touches the owner's run directory. - The signal cannot be re-raised (blocked or ignored, or no way to signal ourselves) — a diagnostic is
printed and the process exits
128+N, explicitly noting that a parent shell will not see death by signal. - On the signal path the caller's trap runs in a subshell, so it sees variables but its own state changes do not reach the dying shell — an honest limit, stated in the header.
- A POSIX-only guard at the top rejects non-bash shells before any bash-only syntax is parsed.
- A re-source guard (
_TMP_RUN_DIR_LOADED, deliberately not exported so a child loads its own copy). - Sources
safe_rm.shfrom beside itself. tmp_run_dir_initnormalisesTMPDIRto an absolute directory, records the original, then installs the signal traps first, reads the EXIT trap this instance really owns, records the owner ($BASHPID, never$$— inside( … ),$( … )or a pipeline stage$$is the parent), installs_tmp_run_dir_exit, and finally allocates the directory withmktemp -d._tmp_run_dir_exitacts only in the owner instance, cleans up, then runs the chained caller trap with the original status._tmp_run_dir_on_signalblocks further signals, takes the pending chain, cleans up, removes the traps, runs the chain in a subshell, then re-raises the signal on$BASHPID.tmp_run_dir_cleanuprestoresTMPDIRto the absolute parent before removal (sosafe_rm_rfaccepts it), retries the removal, names a failure, then restores the caller's originalTMPDIR.
scripts/lib/safe_rm.sh— the removal primitive (safe_rm_rf), and the reasonTMPDIRis restored first.scripts/lib/test_tmp_run_dir.sh— this library's suite (510 lines; it is what exercises theunset BASHPIDpath).scripts/lib/test_user_bus_env.sh,scripts/lib/test_safe_rm.sh— sibling library suites.- Consumers: tests and scripts that create many temp directories, especially inside
$(...).
2026-12-04 — bash -n scripts/lib/tmp_run_dir.sh → exit 0 (a library: sourced, not executed).
Behaviour a reader can repeat (creates and removes one directory):
bash -c '. scripts/lib/tmp_run_dir.sh; tmp_run_dir_init "probe" || exit 2; \
echo "dir=$TMP_RUN_DIR"; d=$(mktemp -d); echo "child=$d"; tmp_run_dir_cleanup; \
[ -d "$TMP_RUN_DIR" ] && echo LEFT-BEHIND || echo removed; [ -d "$d" ] && echo child-left || echo child-gone'Expected: dir=/tmp/probe.XXXXXX, child=/tmp/probe.XXXXXX/tmp.XXXXXX, then removed and child-gone.