Frequently Asked Question

How do I run cleanup code on script exit with trap?

The trap builtin registers a piece of shell code to run when the script receives a specified signal, or when it exits for any reason. The most useful pattern is trap cleanup EXIT, where cleanup is a function you have defined. Bash will run cleanup whether the script finished normally, hit set -e and aborted, was killed by Ctrl+C, or terminated for any other reason. That makes it the right place to remove temporary files, undo mkdir -p, kill child processes, or release locks.

The classic temp-file idiom is tmp=$(mktemp); trap 'rm -f "$tmp"' EXIT, set up immediately after creating the file so there is no window where a crash could leak it. You can trap specific signals too: trap 'echo interrupted; exit 130' INT catches Ctrl+C and exits with the conventional signal-2 status. Multiple traps for the same signal overwrite each other, there is one handler per signal, so define one cleanup function and put everything in it. The ERR pseudo-signal fires on any command failure and pairs well with set -e for diagnostic logging.

Video

Further reading and video