The trap command in Bash is used to catch and handle signals, interruptions, and specific events in a script. It allows you to define actions that should be taken when certain signals are received, enabling you to manage unexpected behavior gracefully.
Key Features of trap:
-
Signal Handling: You can specify commands to execute when the script receives signals like
SIGINT(interrupt),SIGTERM(termination), etc. -
Cleanup Actions: It is commonly used to perform cleanup tasks, such as deleting temporary files or closing network connections, before the script exits.
-
User Interrupts: You can handle user interrupts (like pressing Ctrl+C) to ensure that the script exits cleanly.
Basic Syntax:
trap 'commands' SIGNAL
Example:
#!/bin/bash
# Define a cleanup function
cleanup() {
echo "Cleaning up..."
rm -f temp_file.txt
}
# Set trap for SIGINT (Ctrl+C)
trap cleanup SIGINT
# Main script logic
echo "Running script. Press Ctrl+C to interrupt."
while true; do
sleep 1
done
In this example, if the user presses Ctrl+C, the cleanup function will be called, allowing the script to perform cleanup before exiting.
