Trapping Signals in Shell Scripts
The trap
command is the primary mechanism for handling signals in shell scripts. It allows you to specify a command or function to be executed when a specific signal is received by the script.
The trap
Command Syntax
The basic syntax for the trap
command is as follows:
trap 'command' signal [signal ...]
Here, 'command'
is the action to be performed when the specified signal(s)
are received. The signals can be specified by their names (e.g., SIGINT
, SIGTERM
) or their numeric values.
Trapping Multiple Signals
You can trap multiple signals by providing a space-separated list of signal names or numbers. For example:
trap 'echo "Script interrupted"; exit 1' SIGINT SIGTERM
In this case, the script will execute the echo "Script interrupted"; exit 1
command when either the SIGINT
(Ctrl+C) or SIGTERM
signal is received.
Resetting Signal Traps
If you want to reset the signal trap to the default behavior, you can use the trap
command with no arguments:
trap - SIGINT SIGTERM
This will remove the trap and restore the default signal handling for the specified signals.
Trapping the EXIT Signal
The EXIT
signal is a special signal that is triggered when the script is about to exit. You can use this signal to perform cleanup or other actions before the script terminates:
trap 'echo "Script is exiting"; cleanup_resources' EXIT
By understanding and effectively using the trap
command, you can create shell scripts that can gracefully handle various signals and events, making your scripts more robust and reliable.