Session and utilities

The trap command

Runs a command when the shell receives a signal or exits.

Syntax

trap 'accion' SENALTry it in the terminal →

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

MessageCauseFix
bash: trap: NOSUCH: invalid signal specificationThe 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 optiontrap 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

  • kill: sends a signal to a process. trap decides what your script does when it receives one.
  • exit: ends the shell with a code. The EXIT trap also runs when you leave with exit.
  • set -e: makes the shell exit when a command fails. ERR runs in those same cases, but it does not end the script by itself.

Related 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