Stop your shell scripts from getting lost when your trap command backfires
By Saket Jain Published Linux/Unix
Stop your shell scripts from getting lost when your trap command backfires
Technical Briefing | 7/26/2026
You spend half an hour writing a cleanup routine in a trap statement. It tests fine when you hit Ctrl+C, but then a deployment script runs it non-interactively and leaves a pile of temp files and lockfiles all over /tmp. This bit me in prod during a server migration, and it turns out that relying on signals is harder than the man pages lead you to believe.
Signals are not just about your keyboard
Most people only think of SIGINT because that is what happens when you reach for the escape key. But your shell scripts are constantly bombarded with other signals, especially when managed by systemd or orchestration tools. If you only catch SIGINT, you are leaving your script wide open to leaving garbage behind when a service restart sends SIGTERM.
cleanup() { rm -f /tmp/myapp.lock; exit; }; trap cleanup EXIT TERM INT HUP
- The EXIT signal is your best friend because it triggers regardless of how the script terminates
- Multiple signals can be chained in one trap call to keep your boilerplate readable
- Using a function for your cleanup ensures you do not have to write the same logic three times
Why simple traps often fail in subshells
If you are running command substitution or background jobs, those child processes often don’t inherit the trap. This is a common silent failure. If your script runs a subshell and it gets hit with a kill command, the parent script might not even know it died, let alone trigger the cleanup function. Try moving your lockfile logic into a dedicated lock-manager script that uses a reliable PID check instead of just hoping your trap fires.
Next time you are drafting a long-running automation task, spend an extra minute thinking about the death sequence of your process. Being defensive about your environment cleanup is how you stop being the person who gets paged because the disk filled up with orphaned temp files.
