Bash traps are a powerful feature that allow scripts to catch and respond to signals or events. They provide a way to execute specific commands when certain conditions are met, such as script termination or user interruption.
A trap in Bash is a mechanism that intercepts signals sent to a script. It enables developers to define custom behaviors when these signals occur. This functionality is particularly useful for cleanup operations, graceful exits, and handling unexpected terminations.
The basic syntax for setting a trap in Bash is:
trap 'commands' SIGNALS
Here, 'commands' represent the actions to be executed when the specified SIGNALS are received.
One of the most common uses of traps is to perform cleanup operations when a script exits:
trap 'echo "Cleaning up..."; rm -f temp_file.txt' EXIT
This trap will execute the specified commands whenever the script exits, ensuring that temporary files are removed.
Traps can also be used to catch user interrupts (Ctrl+C) and perform custom actions:
trap 'echo "Script interrupted. Exiting..."; exit 1' SIGINT
You can set a trap for multiple signals in a single command:
trap 'echo "Caught signal"; exit 1' SIGINT SIGTERM
To remove a previously set trap, use the - option:
trap - SIGINT
To further enhance your Bash scripting skills, explore these related topics:
By mastering Bash traps, you'll be able to create more robust and reliable scripts that can handle various scenarios gracefully.