Trap Command
Overview
The trap command catches signals and interruptions in your script to handle unexpected events gracefully.
Syntax: trap <arg/function> <signal>
Code
Basic Example
#!/bin/bash
# trap Ctrl+C (SIGINT) and SIGTERM
trap "echo Booh!" SIGINT SIGTERM
echo "it's going to run until you hit Ctrl+Z"
echo "hit Ctrl+C to be blown away!"
while true; do
sleep 60
doneUsing a Function
#!/bin/bash
cleanup() {
echo "Cleaning up..."
rm -f /tmp/mytempfile
exit 0
}
trap cleanup SIGINT SIGTERM
# main script logic
while true; do
sleep 60
doneCommon Use Cases
# cleanup temporary files on exit
trap "rm -f /tmp/tempfile; exit" 2 15
# cleanup on any exit (including normal)
trap "rm -rf $TMPDIR" EXIT
# ignore a signal
trap "" SIGINT
# reset trap to default behavior
trap - SIGINTDetails
Common Signals
| Number | Signal | Description |
|---|---|---|
| 2 | SIGINT | User sends interrupt (Ctrl+C) |
| 3 | SIGQUIT | User sends quit (Ctrl+D) |
| 8 | SIGFPE | Attempted illegal mathematical operation |
| 9 | SIGKILL | Kill (cannot be trapped) |
| 15 | SIGTERM | Termination signal |
List all available signals:
kill -lYou can use signal numbers instead of names:
# 2 = SIGINT, 15 = SIGTERM
trap cleanup 2 15Appendix
Note created on 2025-12-23 and last modified on 2025-12-23.
See Also
Backlinks
(c) No Clocks, LLC | 2025