trap
shell scriptingLinux/Unix
The trap command is one of the most frequently used commands in Linux/Unix-like operating systems. trap Set up signal handlers in shell scripts
Quick Reference
Command Name:
trap
Category:
shell scripting
Platform:
Linux/Unix
Basic Usage:
trap [options] [arguments]
Common Use Cases
Syntax
trap [OPTIONS] [[ARG] SIGNAL...]
Options
Option | Description |
---|---|
-l |
List signal names and their corresponding numbers |
-p |
Display the trap commands associated with each SIGNAL |
--help |
Display help information and exit |
--version |
Output version information and exit |
Common Signal Names | |
SIGHUP (1) |
Hangup detected on controlling terminal or death of controlling process |
SIGINT (2) |
Interrupt from keyboard (Ctrl+C) |
SIGQUIT (3) |
Quit from keyboard (Ctrl+\) |
SIGILL (4) |
Illegal instruction |
SIGTRAP (5) |
Trace/breakpoint trap |
SIGABRT (6) |
Abort signal from abort(3) |
SIGKILL (9) |
Kill signal (cannot be caught or ignored) |
SIGTERM (15) |
Termination signal |
SIGSTOP (17,19,23) |
Stop process (cannot be caught or ignored) |
SIGTSTP (18,20,24) |
Stop typed at terminal (Ctrl+Z) |
SIGCONT (19,18,25) |
Continue if stopped |
SIGWINCH (28,28,26) |
Window resize signal |
EXIT (0) |
Exit from shell (not a real signal, but often used with trap) |
ERR |
Execute on error (not a real signal, Bash-specific) |
DEBUG |
Execute before every command (not a real signal, Bash-specific) |
Examples
How to Use These Examples
The examples below show common ways to use the trap
command. Try them in your terminal to see the results. You can copy any example by clicking on the code block.
# Basic Examples Basic
# Display a message when the script is interrupted with Ctrl+C
trap "echo 'Script interrupted'" SIGINT