Stop trap signals from killing your cleanup scripts midway
By Saket Jain Published Linux/Unix
Stop trap signals from killing your cleanup scripts midway
Technical Briefing | 10/6/2026
We have all written those scripts that create temporary state: lock files, scratch directories, or network sockets that need to be wiped when the work is done. You put a cleanup function at the bottom and maybe call it at the end. But when your script gets hit with a SIGTERM or the user panics and mashes Ctrl-C, that cleanup code never fires. You are left with a system littered with stale state that breaks the next run.
The signal handling dance
Most people forget that a shell script isn’t just a list of commands executed in order; it is a process that can be interrupted at any moment. When you don’t explicitly catch signals like SIGINT or SIGTERM, the shell just dies immediately. To prevent this, you have to trap these signals and route them to your cleanup function. It is a small addition, but it makes your automation significantly more predictable when things go sideways.
cleanup() { rm -rf "$TMP_DIR"; exit; }; trap cleanup EXIT INT TERM; TMP_DIR=$(mktemp -d); # run your heavy tasks here
- Use the EXIT signal to catch natural completion and failures
- Include INT and TERM specifically to handle keyboard interrupts and system termination requests
- Always use double quotes around variables to keep globbing from ruining your day
- Place the trap declaration at the very top of your script so it is active before the first line runs
If you are running these scripts under a scheduler like systemd, catching these signals becomes even more critical because the init system sends a SIGTERM before escalating to a SIGKILL. If your script doesn’t handle the exit gracefully, you are forcing the system to clean up for you, which usually means your lock files stay exactly where they are. Take ten seconds to add a trap, and you will stop cleaning up after your own automation.
