What Is a Trap? Running Cleanup on Signals and Exit
A trap is a shell mechanism that runs a specified command when the shell receives a particular signal or is about to exit, used for cleanup.
When a script is interrupted or finishes, you often want to clean up: delete temp files, stop a background server, remove a lock. The trap command lets you register code that runs on those events. In CI, traps make sure cleanup happens even when a step fails or is cancelled partway through.
What a trap is
The trap builtin associates a command with one or more signals or with the special EXIT event. When that signal arrives or the shell exits, the trapped command runs first.
A basic example
Writing trap 'rm -f "$tmpfile"' EXIT ensures the temp file is removed whenever the script ends, whether it succeeds, fails, or is interrupted. The cleanup is centralized in one place.
Common trap targets
- EXIT: runs whenever the shell exits, for any reason.
- SIGINT: handles Ctrl-C / interruption.
- SIGTERM: handles a polite termination request.
- ERR: runs when a command fails (with set -e).
Why traps matter
Without a trap, an early failure can leave temp files, running processes, or locks behind. A trap guarantees teardown logic runs once, no matter how the script ends, which keeps environments clean.
Traps in CI
CI steps that start background services or create temp resources should trap EXIT to tear them down. When a job is cancelled or times out, the runner sends a signal; trapping it lets the step flush logs or stop services before the environment disappears.
Clean teardown on managed runners
On Latchkey runners, the platform sends a termination signal before tearing down. A trap on EXIT or SIGTERM gives your step a chance to stop a background server or save artifacts cleanly when a run is cut short.
Key takeaways
- A trap runs a command when the shell gets a signal or exits.
trap ... EXITcentralizes cleanup that runs no matter how a script ends.- In CI, traps ensure temp files and background services are cleaned up reliably.