Bash Trap on Exit and Cleanup
An EXIT trap is a cleanup command that runs when a script ends. One trap can run a whole cleanup routine, so temporary files do not survive the script.
Cleanup runs when the script ends
The trap prints a fixed cleanup line. It appears after the work line, when the script ends on its own.
trap 'echo "cleanup done"' EXIT
echo "work done"Cleanup still runs after an explicit exit
The script exits in the middle, so the line after exit never prints. The cleanup line still appears, because exit triggers the trap.
trap 'echo "cleanup done"' EXIT
echo "before exit"
exit 0
echo "skipped step"A temporary directory is removed on exit
The script creates a temporary directory and checks that it exists. The trap removes it when the script ends, and only a fixed label is printed.
dir=$(mktemp -d)
trap 'rm -rf "$dir"; echo "temp removed"' EXIT
if [ -d "$dir" ]; then echo "temp dir ready"; fi
echo "work done"Example
remove_temp_file() {
rm -f "$tempfile"
echo "temp file removed"
}
remove_temp_dir() {
rm -rf "$tempdir"
echo "temp dir removed"
}
cleanup() {
remove_temp_file
remove_temp_dir
}
tempfile=$(mktemp)
tempdir=$(mktemp -d)
trap cleanup EXIT
if [ -f "$tempfile" ] && [ -d "$tempdir" ]; then echo "temp ready"; fi
echo "work done"Key points
- One trap wins: a second EXIT trap replaces the first, so combine all steps into one cleanup function.
- Normal and explicit exits: the trap runs when the script ends normally and when it calls exit.
- Signal limit: a signal that kills the script outright, like SIGKILL, gives no trap a chance to run.
- Fixed labels only: cleanup should print fixed text, never a temporary path.
- Safe rerun: cleanup steps should succeed even if a resource is already gone.
- Install once: set the trap once and let one cleanup function call every step.
In this example, two small helpers remove one temporary file and one temporary directory. A single cleanup function calls both helpers, and one EXIT trap runs that function. The trap is set after the resources exist, and the cleanup lines appear after the work line when the script ends.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What happens if a script sets two different EXIT traps?