Stop trap signals from killing your cleanup logic
Technical Briefing | 7/15/2026
We have all written those scripts that create temporary directories or lock files. You add a quick removal line at the end, but then a power outage or a stray kill -9 happens and your filesystem ends up looking like a disaster zone. Most people rely on the script finishing naturally, but that is a gamble you lose eventually.
Why your cleanup block is probably failing
The shell is remarkably good at ignoring what happens after it gets a termination signal. If you just define a function to clean up, you need to actually hook it into the shell environment. Using trap ensures that whether your script finishes normally, hits an error, or gets a polite request to terminate from systemd, your environment stays tidy.
cleanup() { rm -rf /tmp/scratch-$$; exit; }; trap cleanup EXIT SIGTERM SIGINT
- Use EXIT to catch the normal end of the script or manual exits
- Include SIGTERM to handle controlled shutdowns from your process manager
- Catch SIGINT so that hitting Ctrl+C triggers your cleanup instead of leaving state behind
One trap I’ve fallen into is forgetting that signals don’t propagate to child processes automatically. If you are spawning background jobs, your trap needs to explicitly kill those children first, otherwise they become zombies or orphans still holding onto your lock files. Put your trap definition at the very top of your script, right after your variables, and you will save yourself a massive amount of cleanup headaches down the line.
