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.
- Description
- Syntax
- Examples
- Related commands
- Linux commands help
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
Examples
trap -l
Display a list of signal names and their corresponding numbers. The list resembles the following:
- SIGHUP 2) SIGINT 3) SIGQUIT 4) SIGILL 5) SIGTRAP
- SIGABRT 7) SIGBUS 8) SIGFPE 9) SIGKILL 10) SIGUSR1
- SIGSEGV 12) SIGUSR2 13) SIGPIPE 14) SIGALRM 15) SIGTERM
- SIGSTKFLT 17) SIGCHLD 18) SIGCONT 19) SIGSTOP 20) SIGTSTP
- SIGTTIN 22) SIGTTOU 23) SIGURG 24) SIGXCPU 25) SIGXFSZ
- SIGVTALRM 27) SIGPROF 28) SIGWINCH 29) SIGIO 30) SIGPWR
- SIGSYS 34) SIGRTMIN 35) SIGRTMIN+1 36) SIGRTMIN+2 37) SIGRTMIN+3
- SIGRTMIN+4 39) SIGRTMIN+5 40) SIGRTMIN+6 41) SIGRTMIN+7 42) SIGRTMIN+8
- SIGRTMIN+9 44) SIGRTMIN+10 45) SIGRTMIN+11 46) SIGRTMIN+12 47) SIGRTMIN+13
- SIGRTMIN+14 49) SIGRTMIN+15 50) SIGRTMAX-14 51) SIGRTMAX-13 52) SIGRTMAX-12
- SIGRTMAX-11 54) SIGRTMAX-10 55) SIGRTMAX-9 56) SIGRTMAX-8 57) SIGRTMAX-7
- SIGRTMAX-6 59) SIGRTMAX-5 60) SIGRTMAX-4 61) SIGRTMAX-3 62) SIGRTMAX-2
- 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$$.
Related commands
csh — The C shell command interpreter.exit — Exit the command shell.ksh — The Korn shell command interpreter.sh — The Bourne shell command interpreter.