Session and utilities
The trap command
Runs a command when the shell receives a signal or exits.
Most useful options
-lLists signal names and their numbers. With no signals, it lists all of them.-pShows the defined actions in a format you can run again as shell input.-PShows only the action of the signals you name. Only since bash 5.3.--Marks the end of options: what follows is not read as an option.Copy-ready examples
$ trap 'echo adios' EXIT; echo finsets an action for exit and tests it: it first prints fin, and on exit, adios.Example output
fin adios
$ trap 'echo adios' EXIT; trap -p EXITshows the action registered for EXIT in a reusable format.Example output
trap -- 'echo adios' EXIT adios
$ tmp=$(mktemp) && trap 'rm -f "$tmp"' EXITcreates a temporary file and deletes it when the script exits, even if it fails.$ trap 'echo "fallo en la línea $LINENO" >&2' ERRwarns when a command fails. It does not fire in the conditions of if or while, the same as set -e.$ trap '' INTignores Ctrl+C: an empty string makes the signal be discarded.You can try them in the browser terminal: it does not touch your computer.
Common errors
| Message | Cause | Fix |
|---|---|---|
| bash: trap: NOSUCH: invalid signal specification | The name is not a known signal and may be a typo. The SIG prefix is optional and case does not matter. | List the valid names with trap -l and write one of them, for example INT or SIGINT. |
| bash: trap: -x: invalid option | trap only accepts -l, -p, -- and, since bash 5.3, -P. You typed another letter with a dash. | Use trap -p to see the actions or trap -l to see the signals. |
Typical mistakes
- With double quotes, $x expands when the trap is defined, not when it runs. With single quotes the expansion is delayed.
- A signal already ignored when a non-interactive shell starts cannot be trapped or reset.
- Defining a trap again replaces the previous one for that signal: trap does not stack actions.
Differences from similar commands
FAQ
What does trap show with no arguments?
The current actions in a reusable format, the same as trap -p.
How do I restore a signal to its original action?
With trap - SIGNAL. It goes back to the value it had when the shell started.
Are traps inherited by a subshell?
No. Signals that were not ignored go back to their original values when a subshell is created.
Learn to actually use it
The basic Linux course takes you from zero to console fluency with 24 self-grading lessons.
Start the free course