06. Bash trap Command
The trap command in Bash lets you catch signals sent to a script and run custom code when those signals occur.
It is commonly used to:
-
Handle interruptions (like
Ctrl + C) -
Perform cleanup before exit
-
Prevent accidental termination
-
Handle script errors safely
1. What is a Signal?¶
A signal is a notification sent to a process to inform it that an event occurred.
Common signals:
| Signal | Name | Trigger |
|---|---|---|
INT |
Interrupt | Ctrl + C from keyboard |
TERM |
Terminate | kill <pid> default signal |
KILL |
Kill | kill -9 <pid> (cannot trap) |
EXIT |
Exit | Script finishes execution |
ERR |
Error | Command fails (non-zero status) |
2. Basic Syntax¶
or using a function:
3. Example: Detect Ctrl + C (INT Signal)¶
Script¶
#!/bin/bash
# 06. Bash trap Command
trap bashtrap INT
# Function executed on CTRL+C
bashtrap() {
echo "CTRL+C Detected!... executing bash trap!"
}
# Loop from 1 to 10
for a in $(seq 1 10); do
echo "$a/10 to Exit."
sleep 1
done
echo "Exit Bash Trap Example!!!"
What Happens¶
-
When
Ctrl + Cis pressed:-
Bash sends the INT signal
-
trapcatches it -
Function
bashtrap()runs -
Script continues execution
-
Output (Sample)¶
1/10 to Exit.
2/10 to Exit.
^CCTRL+C Detected!... executing bash trap!
3/10 to Exit.
...
10/10 to Exit.
Exit Bash Trap Example!!!
4. Trap Multiple Signals¶
You can trap multiple signals at once.
5. Example: Cleanup Before Exit¶
Useful for deleting temp files, stopping services, restoring settings.
#!/bin/bash
cleanup() {
echo "Cleaning up resources..."
rm -f temp.txt
}
trap cleanup EXIT
echo "Temporary data" > temp.txt
echo "Script running..."
sleep 3
What Happens¶
-
When script exits normally or due to interruption
-
cleanup()runs automatically
6. Prevent Script From Being Killed Easily¶
You can ignore signals.
Now Ctrl + C will not stop the script.
7. Restore Default Behavior¶
Removes the custom trap and restores default signal handling.
8. Trap Errors¶
Run a function when any command fails.
#!/bin/bash
error_handler() {
echo "An error occurred!"
}
trap error_handler ERR
ls /nonexistent
echo "This will still run"
9. Common Use Cases¶
Graceful Shutdown¶
Temporary File Cleanup¶
Debugging¶
10. Important Notes¶
-
SIGKILLcannot be trapped -
Use quotes to avoid early variable expansion
-
Traps apply to the current shell and subshells differently
-
EXITtrap always runs when script finishes
11. Best Practices¶
-
Always use traps for cleanup in production scripts
-
Combine
EXIT+INTfor reliability -
Keep trap handlers lightweight
-
Avoid complex logic inside trap functions
12. Quick Reference¶
| Task | Command |
|---|---|
| Catch Ctrl+C | trap handler INT |
| Cleanup on exit | trap handler EXIT |
| Ignore Ctrl+C | trap '' INT |
| Restore default | trap - INT |
| Catch errors | trap handler ERR |
If you're writing automation, pentesting scripts, or long-running recon tools, trap is essential for safe interruption and cleanup.