The trap
command in Bash is used to specify commands that will be executed when the shell receives certain signals or when specific events occur. This is particularly useful for handling cleanup tasks or managing the behavior of scripts when they are interrupted.
The basic syntax of the trap
command is as follows:
trap [commands] [signals]
commands
: The commands to execute when the specified signals are received.signals
: The signals that will trigger the execution of the commands.SIGINT
: Triggered by pressing Ctrl+C.SIGTERM
: The default signal sent by the kill
command.EXIT
: Executes commands when the script exits, regardless of the reason.ERR
: Executes commands when a command fails (returns a non-zero status).To remove a temporary file when the script exits:
trap 'rm -f /tmp/mytempfile' EXIT
To display a message and exit gracefully when the script is interrupted:
trap 'echo "Script interrupted!"; exit' SIGINT
To handle both SIGINT and SIGTERM with the same command:
trap 'echo "Terminating..."; exit' SIGINT SIGTERM
To print a message when a command fails:
trap 'echo "An error occurred!"' ERR
trap
are simple and quick to execute, as they will run in response to signals.trap
to manage resources effectively, especially in scripts that create temporary files or open network connections.trap
commands behave as expected under different scenarios.