Bash by Example: Trap Signals
Handling interrupts and cleanup using the trap command to catch signals like SIGINT, SIGTERM, and EXIT, implementing cleanup functions that execute when scripts are interrupted or terminated, ensuring temporary files are removed, releasing resources properly, and creating robust scripts that handle interruptions gracefully.
Code
#!/bin/bash
# Define a cleanup function
cleanup() {
echo -e "\nCaught signal! Cleaning up..."
rm -f temp_data.txt
echo "Cleanup done. Exiting."
exit 1
}
# Trap SIGINT (Ctrl+C) and SIGTERM
trap cleanup SIGINT SIGTERM
echo "Script started. PID: $$"
echo "Creating temp file..."
touch temp_data.txt
echo "Doing work (Press Ctrl+C to test trap)..."
count=0
while [ $count -lt 10 ]; do
sleep 1
echo -n "."
((count++))
done
echo -e "\nNormal completion."
# Manual cleanup if no signal caught
rm -f temp_data.txtExplanation
Scripts often create temporary files, start background processes, or modify system state. If a user presses Ctrl+C to stop the script midway, or if the system sends a termination signal, these resources might be left in an inconsistent state (e.g., "orphan" temp files). The trap command allows you to "catch" these signals and execute a specific command or function before the script exits.
The syntax is trap command signals. Common signals to trap include SIGINT (Interrupt, triggered by Ctrl+C), SIGTERM (Termination, the default kill signal), and EXIT (triggered whenever the script exits, regardless of success or failure). Trapping EXIT is particularly powerful for ensuring cleanup code runs even if the script crashes due to a syntax error or set -e.
It is best practice to define a cleanup function and register it with trap at the very beginning of your script. This ensures that no matter what happens during execution, your script leaves the system clean.
Code Breakdown
trap cleanup SIGINT SIGTERM registers the cleanup function. If the user hits Ctrl+C, Bash pauses the current command, runs cleanup, and then exits (because cleanup calls exit).temp_data.txt. Without this, a Ctrl+C would leave that file on the disk.
