command is used for two purposes:
- execute a command or sequence of commands when the shell receives a signal.
- inhibit the shell from acting upon a signal.
The syntax is
trap [ arg ] [ sig ]
Now, the trap
command can be used to "catch" signals and perform certain actions based on the signal value. In the format, shown above, arg
is a command to be read and executed when the shell receives signal sig
; note that arg
is scanned once when the trap is set and once when the trap is taken. Each sig
can be given a number or as the name of the signal. Trap commands are executed in order of signal number. Any attempt to set a trap on a signal that was ignored on entry to the current shell is ineffective; note that "the current shell" will be a running shell program (shell programs are forked and executed in a new shell.
conditions are valid:
- If arg is omitted or is -, then all trap(s) sig are reset to their original values.
- If arg is the null string then this signal is ignored by the shell and by the commands it invokes.
- If sig is ERR then arg will be executed whenever a command has a nonzero exit code -- this trap is not inherited by shell functions.
- If sig is 0 (zero) or EXIT and the trap statement is executed inside the body of a function, then the command arg is executed after the function completes.
- If sig is 0 (zero) or EXIT for a trap set outside any function arg is executed on exit from the shell.
# Exit on signal 2
trap 'exit' 2
# Null trap
trap ':' 2 3
# Ignoring Signales
trap ' ' 1 2 3 15
# Trapping a trap
trap 'trap "" 1 2 3 15; rm -f tmp*' 1 2 3 15
# Resetting Trap for Signals 2 and 3
trap 2 3
Signal Name Meaning
1 HUP hangup -- the user has logged off
2 INT interrupt -- the user has pressed the intr key
3 QUIT Quit -- the user has pressed the quit key
9 KILL Kill (cannot be ignored)
15 TERM Software termination
10 BUS Bus error, usually a programming error
11 SEGV Segmentation programming error
14 ALRM Alarm timeout
24 TSTP Terminal stop -- user has pressed the susp key
Command Purpose Example
trap cmd sig Set trap for cmd on sig trap exit 2
trap sig Reset trap for sig trap 2
trap '' sig Ignore signal sig trap '' 2
The above are Bourne shell and KornShell syntax; I believe they're identical in BASH -- check your manual page(s).
Hope this helps some.