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 are listed along with what triggers them.
Exit from shell (usually when shell script finishes).
Hangup (usually logout).
Interrupt (usually CTRL-C).
Quit.
Illegal instruction.
Trace trap.
IOT instruction.
EMT instruction.
Floating point exception.
Bus error.
Bad argument to a system call.
Write to a pipe without a process to read it.
Alarm timeout.
Software termination (usually via kill).
Nonzero exit status. Korn shell only.
Execution of any command. Korn shell only.
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