Bash Signals and Traps
A trap runs a command when a signal arrives or when the script ends. Traps let a script clean up and report errors instead of stopping silently.
Clean up with an EXIT trap
The cleanup function is registered for the EXIT event. The main work prints first, and the cleanup line prints as the script ends.
cleanup() {
echo "cleaning up"
}
trap cleanup EXIT
echo "work done"Catch a failure with an ERR trap
The false command fails, so the ERR trap prints its line. The script then keeps running and prints its next line.
trap 'echo "error caught"' ERR
false
echo "script continues"Catch a signal sent to the script itself
The trap catches the interrupt signal sent to the script itself. The script then keeps running, and no process number is printed.
trap 'echo "interrupt caught"' INT
kill -INT $$
echo "after signal"Example
trap 'echo "error noted"' ERR
trap 'echo "cleanup done"' EXIT
echo "step one"
false
echo "step two"Key points
- trap: registers a command to run when a named event happens.
- EXIT: an event that fires when the script ends, for cleanup.
- ERR: an event that fires when a simple command fails.
- INT and TERM: signals that ask a script to stop; a trap can catch them.
- A trap handler prints fixed text only, never a process number or a changing value.
- EXIT traps are the most predictable: they run at the end, every time.
In this example, two traps are registered first: one for errors and one for the end of the script. The first step prints, then the false command fails and the error trap prints its line. The second step prints next. As the script ends, the EXIT trap prints the cleanup line.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
When does an EXIT trap run?