trap ['handler'] [event …]
trap intercepts certain kinds of exception conditions. Any signal may be intercepted by specifying an event corresponding to the signal number.
With an event of ERR, trap invokes the handler after receiving any having a nonzero exit status. The exception to this is conditions in if, while, and until statements. This trap is not inherited within a function.
With a trap number of 0 or EXIT, trap invokes the handler during exit from the shell. Within a function, it is invoked during exit from the function.
Any other event corresponds to a signal number or signal name. (See kill for a table of valid signal numbers and their names.) If a signal is being ignored when you enter the shell, the shell continues to ignore it without regard to any traps.
Because system initialization sets the value of the SIGIOERR signal to ignore, this signal cannot be set by trap.
The handler argument is a command list. It is usually more than one word, and so you must quote it to appear as a single argument. It is scanned when the trap function is initially invoked. When the trap condition is raised, the shell scans the command list again and runs the commands. A missing argument or an argument of - (dash) resets the default trap condition. A null argument ('') causes the trap condition to be ignored.
If there are no arguments at all, trap prints a list of all the traps and their commands.
trap is a special built-in shell command.
trap 'rm –f /tmp/xyz$$; exit' ERR EXIT
trap 'read REPLY?"ABORT??"
case $REPLY in
y) exit 1;;
esac' 2
trap 'cp $HISTFILE $HOME/old_hist.bak; exit' ALRM
See Localization for more information.
POSIX.2, X/Open Portability GuideX/Open Portability Guide.
sh