next up previous contents
Next: Tips Using Shell Commands Up: Programming the Shell Previous: set: Change Command-line Parameters   Contents

trap: Trap signals

Processes may be sent signals using either the kill command, or a control key combination such as CTRL-C. The interrupt signal (CTRL-C) usually kills the process.

Table 1.1 taken from [6, p. 883] shows some of the signals used in Shell Programming.


Table 1.1: Signal numbers for trap command.
Signal Number Signal Name Explanation
0 Normal exit exit command.
1 SIGHUP When session disconnected.
2 SIGINT Interrupt - often CTRL-c.
15 SIGTERM From kill command.


The trap command typically appears as one of the first lines in the shell script. It contains the commands to be executed when a signal is detected as well as what signals to trap.

#!/bin/sh
TMPFILE=/usr/tmp/junk.$$
trap 'rm -f $TMPFILE; exit 0' 1 2 15 
.
.
.

Upon receiving signals 1, 2 or 15, $TMPFILE would be deleted and the script would terminate the shell script normally. This shows how trap may be used to clean up before exiting.

#!/bin/sh
TMPFILE=/usr/tmp/junk.$$
trap '' 0 1 2
.
.
.

The above example shows how trap may be used to ignore specific signals (0, 1 and 2), while NOT interrupting the current line of execution.

NOTE that when the signal is received, the command currently being executed is interrupted (except in the case where there is nothing to be executed between the two quotation signs), and execution flow continues at the next line of the script.


next up previous contents
Next: Tips Using Shell Commands Up: Programming the Shell Previous: set: Change Command-line Parameters   Contents
Claude Cantin 2010-10-24