The trap command in a Bash script is used to catch specific signals and define actions to be taken when those signals are received. It allows you to handle interruptions gracefully, perform cleanup actions, or execute specific commands before the script exits unexpectedly.
For example, you can use trap to ensure that temporary files are deleted or network connections are closed when the script is terminated. This makes your scripts more robust and user-friendly by managing unexpected terminations and user interrupts effectively.
Here’s a simple example of using trap:
#!/bin/bash
# Define a cleanup function
cleanup() {
echo "Cleaning up..."
rm -f /tmp/tempfile
}
# Set trap to call cleanup on EXIT signal
trap cleanup EXIT
# Main script logic
echo "Running script..."
touch /tmp/tempfile
# Simulate some work
sleep 10
In this example, when the script exits, whether normally or due to an interrupt, the cleanup function will be called to remove the temporary file.
