|Lesson 8|| Trapping system signals|
|Objective|| Use the |
trap command to handle signals sent to a shell script.
Trapping System Signals
At times, you may want to disable a users ability to stop a script. For example, if a user enters CTRL+C while a file is being created by your script,
the file might end up half written or not be created at all.
Signals are short messages sent to your script by other programs such as the shell. When a script receives a signal, it takes an action depending on which signal is received.
For example, pressing CTRL+C sends an interrupt signal to your script. By default, a script will die when you press CTRL+C. Dying is the default action taken when a script receives an interrupt signal.
command to modify the action taken by your script when it receives a signal. Include the
command near the beginning of your script.
This modifies the action taken for a signal until the script ends or until you reset the action with another
command takes a command to be run as its first argument. This is the action that the script will take when it receives the signal specified in the second argument.
Signals are specified by number with the
command. The number two represents the interrupt signal Here, you can see a list of commonly used signals and their numbers
commonly used signals
trap command tells your script to run the given
echo command when it receives signal number 2, the interrupt signal.
trap echo CTRL+C is not allowed 2
To reset your script's behavior back to the default, use
trap with the signal number without including
a command to run. The default action when a script receives an interrupt signal is to die.
If you include an empty string in your
trap command, there is no action when your script receives the
signal. When the user types CTRL + C, nothing will happen.