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 are listed along with what triggers them:
0 | Exit from shell (usually when shell script finishes). |
1 | Hangup (usually logout). |
2 | Interrupt (usually |
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 |
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