Linux trap and onitr command

Updated: 05/04/2019 by Computer Hope
trap command

On Unix-like operating systems, the trap command is a function of the shell that responds to hardware signals and other events.

This page covers the bash built-in version of trap.

Description

trap defines and activates handlers to run when the shell receives signals or other special conditions.

ARG is a command to be read and executed when the shell receives the signal(s) SIGNAL_SPEC. If ARG is absent (and a single SIGNAL_SPEC is supplied) or ARG is a dash ("-"), each specified signal is reset to its original value. If ARG is the null string, each SIGNAL_SPEC is ignored by the shell and by the commands it invokes.

If a SIGNAL_SPEC is EXIT (0), ARG is executed upon exit from the shell.

If a SIGNAL_SPEC is DEBUG, ARG is executed before every simple command.

If a SIGNAL_SPEC is RETURN, ARG is executed each time a shell function or a script run by the "." or source built-in commands finishes executing.

A SIGNAL_SPEC of ERR means to execute ARG each time a command's failure would cause the shell to exit when the -e option is enabled.

If no arguments are supplied, trap prints the list of commands associated with each signal.

Syntax

trap [-lp] [[ARG] SIGNAL_SPEC...]

Options

-l Print a list of signal names and their corresponding numbers.
-p Display the trap commands associated with each SIGNAL_SPEC.

Examples

trap -l

Display a list of signal names and their corresponding numbers. The list resembles the following:

 1) SIGHUP	 2) SIGINT	 3) SIGQUIT	 4) SIGILL	 5) SIGTRAP
 6) SIGABRT	 7) SIGBUS	 8) SIGFPE	 9) SIGKILL	10) SIGUSR1
11) SIGSEGV	12) SIGUSR2	13) SIGPIPE	14) SIGALRM	15) SIGTERM
16) SIGSTKFLT	17) SIGCHLD	18) SIGCONT	19) SIGSTOP	20) SIGTSTP
21) SIGTTIN	22) SIGTTOU	23) SIGURG	24) SIGXCPU	25) SIGXFSZ
26) SIGVTALRM	27) SIGPROF	28) SIGWINCH	29) SIGIO	30) SIGPWR
31) SIGSYS	34) SIGRTMIN	35) SIGRTMIN+1	36) SIGRTMIN+2	37) SIGRTMIN+3
38) SIGRTMIN+4	39) SIGRTMIN+5	40) SIGRTMIN+6	41) SIGRTMIN+7	42) SIGRTMIN+8
43) SIGRTMIN+9	44) SIGRTMIN+10	45) SIGRTMIN+11	46) SIGRTMIN+12	47) SIGRTMIN+13
48) SIGRTMIN+14	49) SIGRTMIN+15	50) SIGRTMAX-14	51) SIGRTMAX-13	52) SIGRTMAX-12
53) SIGRTMAX-11	54) SIGRTMAX-10	55) SIGRTMAX-9	56) SIGRTMAX-8	57) SIGRTMAX-7
58) SIGRTMAX-6	59) SIGRTMAX-5	60) SIGRTMAX-4	61) SIGRTMAX-3	62) SIGRTMAX-2
63) SIGRTMAX-1	64) SIGRTMAX
trap

Display a list of the currently-set signal traps.

trap 'rm -f /tmp/xyz$$; exit' ERR EXIT

Set a trap which, on shell error or shell exit, deletes a temporary file xyz$$.

csh — The C shell command interpreter.
exit — Exit the command shell.
ksh — The Korn shell command interpreter.
sh — The Bourne shell command interpreter.