UNIX in a Nutshell: System V Edition

UNIX in a Nutshell: System V EditionSearch this book
Previous: Reference: timesChapter 4
The Bourne Shell and Korn Shell
Next: Reference: type
 

trap

trap [ [commands] signals]

Execute commands if any of signals is received. Common signals include 0, 1, 2, and 15. Multiple commands should be quoted as a group and separated by semicolons internally. If commands is the null string (i.e., trap "" signals), then signals will be ignored by the shell. If commands are omitted entirely, reset processing of specified signals to the default action. If both commands and signals are omitted, list current trap assignments. See examples below and under exec.

Signals

Signals are listed along with what triggers them.

0

Exit from shell (usually when shell script finishes).

1

Hangup (usually logout).

2

Interrupt (usually CTRL-C).

3

Quit.

4

Illegal instruction.

5

Trace trap.

6

IOT instruction.

7

EMT instruction.

8

Floating point exception.

10

Bus error.

12

Bad argument to a system call.

13

Write to a pipe without a process to read it.

14

Alarm timeout.

15

Software termination (usually via kill).

ERR

Nonzero exit status. Korn shell only.

DEBUG

Execution of any command. Korn shell only.

Examples

trap "" 2	Ignore signal 2 (interrupts).
trap 2	Obey interrupts again.

Remove a $tmp file when the shell program exits, or if the user logs out, presses CTRL-C, or does a kill:

trap "rm -f $tmp; exit" 0 1 2 15

Print a "clean up" message when the shell program receives signals 1, 2, or 15:

trap 'echo Interrupt!  Cleaning up...' 1 2 15


Previous: Reference: timesUNIX in a Nutshell: System V EditionNext: Reference: type
Reference: timesBook IndexReference: type

The UNIX CD Bookshelf NavigationThe UNIX CD BookshelfUNIX Power ToolsUNIX in a NutshellLearning the vi Editorsed & awkLearning the Korn ShellLearning the UNIX Operating System