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
fiReport a problem with this exampleOpens a pre-filled issue on GitHub.