trap - Intercept abnormal conditions and interrupts
Format
trap
['
handler'
] [event
...]
Description
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.
Usage notes
trap is a special built-in shell command.
Examples
- On error or exit, this example deletes a temporary file that was created during command
execution.
trap 'rm -f /tmp/xyz$$; exit' ERR EXIT
When an interrupt signal is received, the example prompts whether to abort, and exits if the answer isy
.trap 'read REPLY?"ABORT??" case $REPLY in y) exit 1;; esac' 2
- This example saves your shell history file (specified by the value
you give the HISTFILE environment variable) before timing you out,
so you can restore it when you log on again.
trap 'cp $HISTFILE $HOME/old_hist.bak; exit' ALRM
Localization
- LANG
- LC_ALL
- LC_MESSAGES
- NLSPATH
Exit values
0
- Successful completion.
1
- Failure due to any of the following reasons:
- Incorrect signal name.
- Incorrect signal number.
2
- Incorrect command-line argument.
Messages
- name not a valid trap name
- You specified an unrecognized trap name. The usual cause of this error is a typing mistake on the command line.
Portability
POSIX.2, X/Open Portability GuideX/Open Portability Guide.
Related information
sh