DistributedNetworks DistributedNetworks


Unix Commands  «Prev  Next»
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 user’s 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

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.

trap command

Use the trap command to modify the action taken by your script when it receives a signal. Include the trap 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 trap command.
The trap 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 trap command. The number two represents the interrupt signal Here, you can see a list of commonly used signals and their numbers commonly used signals .

Examples

The following 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.
trap 2

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.
trap “” 2

Trapping SystemSignals-exercise

Click the Exercise link to observe a script that traps a signal.
Trapping System Signals - Exercise
The next lesson wraps up the module.