Common use cases for the trap command in Bash include:
-
Cleanup on Exit: Automatically remove temporary files or release resources when a script exits or is interrupted.
trap 'rm -f /tmp/tempfile; exit' EXIT -
Graceful Handling of Interrupts: Allow scripts to handle user interruptions (like Ctrl+C) gracefully, providing a message or performing cleanup.
trap 'echo "Script interrupted"; exit' SIGINT -
Logging Events: Log messages or actions when specific signals are received, useful for debugging or monitoring.
trap 'echo "Received SIGHUP";' SIGHUP -
Preventing Data Loss: Ensure that critical operations are completed or saved before a script is terminated.
trap 'save_data; exit' SIGTERM -
Custom Signal Handling: Define custom behavior for user-defined signals (SIGUSR1, SIGUSR2) to control script execution.
trap 'echo "Custom signal received";' SIGUSR1 -
Timeouts: Use
trapwithSIGALRMto handle timeouts in scripts.trap 'echo "Timeout occurred"; exit' SIGALRM
These use cases help improve the robustness and reliability of Bash scripts by managing unexpected events and ensuring proper resource management.
