Robust Scripts
Cleanup Traps
Always Remove Temporary Files
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
#!/usr/bin/env bash
tmp="$(mktemp -d)"
cleanup() {
rm -rf "$tmp"
}
trap cleanup EXIT
file="$tmp/report.txt"
printf 'ok\n' > "$file"
echo "${file##*/}"
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.