(The scope of the trap
command is much broader than the following explanation suggests,
but here is one of its uses.) Many times we execute a script and
then realize a mistake was made and press the Break
key to stop the process. It is possible the script created several
files on the system that you would have to search for and manually
delete. Fortunately, the trap
command captures an interrupt. Now you can Break,
let the trap
command capture it and then clean up the files from within the script.
The syntax is:
The trap
waits for a signal sent to the shell,
traps it, and then executes arg. After
setting traps, typing trap
with no args lists all commands associated
with signals.
For example:
$ temp="/tmp/xyz$$" $ trap "rm -f $temp; exit" 0 2 3 15 $ trap 0:rm -f /tmp/xyz18996; exit 2:rm -f /tmp/xyz18996; exit 3:rm -f /tmp/xyz18996; exit 15:rm -f /tmp/xyz18996; exit |
In the first line, a temporary file temp
is defined, whose name includes xyz
and the process id number. The second line sets a trap to remove
the file (without complaining if it doesn't exist yet or if the
remove fails). It then exits the shell if the shell exits (0) or
receives one of a certain set of signals (2, 3, 15), which could
be given by names (INT,
QUIT, TERM).
After setting the trap, trap
with no options, lists all traps. The exit
in the trap is necessary because otherwise the trap would be like
an interrupt routine, returning to execution of the script on receipt
of a signal.
If arg is omitted or is -,
all trap signals are reset to their original
values. If signal is ERR
then arg will be executed whenever a
command has a nonzero exit code. The ERR
trap is not inherited by functions.
If the signal is 0 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 signal is EXIT
for a trap set outside any function then the command arg
is executed on exit from the shell.