Bash trap Cleanup for a Temporary Directory
Create a private temp directory with mktemp and remove it reliably from an EXIT trap, preserving the original exit status and signals.
Code
#!/usr/bin/env bash
set -euo pipefail
umask 077
work_dir=""
cleanup() {
local status=$?
trap - EXIT INT TERM
if [[ -n "$work_dir" && -d "$work_dir" ]]; then
rm -rf -- "$work_dir" || true
fi
exit "$status"
}
trap cleanup EXIT
trap 'exit 130' INT
trap 'exit 143' TERM
work_dir="$(mktemp -d "${TMPDIR:-/tmp}/report.XXXXXX")"
report="$work_dir/report.txt"
{
printf 'generated_at=%s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
printf 'script=%s\n' "${BASH_SOURCE[0]}"
printf 'pid=%s\n' "$"
} > "$report"
cat -- "$report"
printf 'work_dir_before_cleanup=%s\n' "$work_dir"
if [[ "${SIMULATE_FAILURE:-0}" == "1" ]]; then
printf 'simulated failure; cleanup still runs\n' >&2
exit 1
fiWhat the code does
The shebang line is backed by set -euo pipefail: first failure stops the run, unset variables are errors, and a pipeline fails if any stage fails.
The work is delegated to umask, trap, rm and cat, chained through 2 pipes so each stage’s output feeds the next.
A helper function (cleanup) keeps the repeated logic out of the main flow.
The script leans on parameter expansion 3 times, using forms like ${var:-default} so defaults, trimming, and casing happen inside the shell with no external tool.
A trap handles termination signals so temporary state is cleaned up even on early exit.
Statements that matter most here
rm -rf -- "$work_dir" || true
work_dir="$(mktemp -d "${TMPDIR:-/tmp}/report.XXXXXX")"
} > "$report"
Interactive Tools for This Topic
FAQ
- Does the script stop on the first error?
- Yes — `set -euo pipefail` aborts on the first failing command, treats unset variables as errors, and fails the whole pipeline if any stage fails. Nothing continues half-broken.
- Which external commands does the script rely on?
- `umask`, `trap`, `rm`, `cat` must be available on the PATH environment variable; everything else is shell built-in syntax.
Report a problem with this exampleOpens a pre-filled issue on GitHub.