TRAP(1SH) COMMAND REFERENCE TRAP(1SH)
NAME
trap - execute command on a given signal (sh built-in)
SYNOPSIS
trap [ arg ] [ n ]
DESCRIPTION
Arg is a command to be read and executed when the shell
receives the signal(s) n. (Note that arg ss scanned once
when the trap is set and once when the trap is taken.) Trap
commands are executed in order of signal number. If arg is
absent, all trap(s) n are reset to their original values. If
arg is the null string or nonexistent, this signal is
ignored by the shell and by invoked commands. If n is 0, the
command arg is executed on exit from the shell; otherwise
upon receipt of signal n as numbered in signal(3c). Trap
with no arguments prints a list of commands associated with
each signal number.
EXAMPLES
The following command causes interrupts (signal number 2) to
be ignored:
trap '' 2
The following shell script shows a major use for the trap
command. The script puts a copy of the standard input into a
temporary file and then copies the data to the standard
output preceded by the current date. If the interrupt or
hangup signal (signal number 1) is sent to the process, the
temporary file is removed and the exit code is 1. When the
process is finished, the temporary file is removed and the
exit code is 1.
#!/bin/sh
Excode=1
trap 'rm -f /tmp/slowpr.$$;exit $Excode' 0 1 2
while read f
do
echo "$f" >> /tmp/slowpr.$$
done
date
cat /tmp/slowpr.$$
Excode=0
Printed 10/17/86 1
TRAP(1SH) COMMAND REFERENCE TRAP(1SH)
RETURN VALUE
[NO_ERRS] Command completed without error.
[1] One or more of the signal numbers is invalid.
CAVEATS
It is very important to note that command and variable
substitutions are made when the trap command is interpreted
and also when the corresponding commands are executed.
Take, for example, the following commands:
trap "rm -f `ls -d /tmp/foo.*`" 0
trap 'rm -f `ls -d /tmp/foo.*`" 0
The first command tells the shell to remove all files that
matched the pattern /tmp/foo.* at the time the trap command
was interpreted. The second trap command tells the shell to
remove all files that matched pattern at the time the shell
script exits. This means that in the first case, new files
created by the shell script after the trap command was
executed will not be removed.
Signal number 11 (segmentation violation) can not be trapped
at this time. Attempts to do so result in an error.
SEE ALSO
break(1sh), cd(1sh), chdir(1sh), continue(1sh), csh(1csh),
echo(1sh), eval(1sh), exec(1sh), exit(1sh), export(1sh),
hash(1sh), login(1), onintr(1csh), pwd(1sh), read(1sh),
readonly(1sh), return(1sh), set(1sh), sh(1sh), shift(1sh),
test(1sh), times(1sh), type(1sh), ulimit(1sh), umask(1sh),
unset(1sh), wait(1sh), which(1sh), execve(2), signal(3c).
Printed 10/17/86 2
%%index%%
na:72,102;
sy:174,114;
de:288,841;
ex:1129,914;
rv:2187,201;
ca:2388,1043;
se:3431,903;
%%index%%000000000121