Stop trap from leaving your temporary files behind when things go south
By Saket Jain Published Linux/Unix
Stop trap from leaving your temporary files behind when things go south
Technical Briefing | 8/19/2026
You write a script that creates a dozen temp files to stage data before a final upload. Everything works perfectly in your dev environment, but then a network blip causes the process to exit mid-stream. Now your /tmp directory is littered with garbage, and you have to write another script just to clean up the mess. It is sloppy, and frankly, we can do better.
The trap solution that actually works
Most scripts skip cleanup because developers rely on the user to kill the process nicely. But SIGTERM and SIGINT are real-world facts of life. The trap command lets you define a function that runs regardless of how the script ends, whether it exits cleanly or gets nuked by a control-c. Keep it simple and keep it local to the shell execution environment.
tmp_dir=$(mktemp -d)
cleanup() { rm -rf "$tmp_dir"; }
trap cleanup EXIT
# Do your work here
- Use mktemp -d to create a unique sandbox instead of flat files
- The EXIT signal covers normal completion and forced exits
- Adding HUP, INT, and TERM to the trap list makes it bulletproof
One thing to watch out for is that trap runs even if the command succeeds. That is usually exactly what you want, but check your exit codes inside the trap function if you need to preserve data on failure for forensic analysis. It is a small change that saves you from hunting down rogue files at three in the morning.
