start page | rating of books | rating of authors | reviews | copyrights

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: true
 

trap

trap [ [commands] signals]
trap -p

Execute commands if any signals are received. The second form is specific to ksh93; it prints the current trap settings in a form suitable for rereading later.

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), signals are ignored by the shell. If commands are omitted entirely, reset processing of specified signals to the default action. ksh93: if commands is "-", reset signals to their initial defaults.

If both commands and signals are omitted, list current trap assignments. See the Examples here and in 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.

KEYBD

A key has been read in emacs, gmacs, or vi editing mode. ksh93 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: true
Reference: timesBook IndexReference: true

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