🎓 A1Learner
🔍
0 of 45 lessons completed

Bash Resetting Traps

Resetting a trap removes its handler and returns the signal to its default action. Resetting is different from ignoring a signal.

Ignoring a signal lets the script survive it

The empty handler means ignore. The signal arrives, nothing happens, and the script continues.

trap '' USR1
kill -USR1 $$
echo "survived ignored signal"

A handler can reset itself after one firing

The handler prints, then removes itself. The trap listing after it is empty, which proves the handler is gone.

trap 'echo "first handler"; trap - USR1' USR1
kill -USR1 $$
trap -p USR1
echo "handler gone"

Removing an EXIT trap stops its cleanup

The EXIT trap is removed before the script ends. No cleanup line prints, which proves the trap is gone.

trap 'echo "cleanup done"' EXIT
echo "work done"
trap - EXIT

Example

trap 'echo "first handler"; trap - USR1' USR1
kill -USR1 $$
trap -p USR1
trap 'echo "second handler"' USR1
kill -USR1 $$
trap -p USR1

Key points

  • trap - SIG: removes the handler for one signal.
  • trap '' SIG: ignores the signal; the script keeps running when it arrives.
  • Ignore is not reset: an ignored signal does nothing, while a reset signal takes its default action.
  • One-shot trap: a handler that runs trap - on itself fires only once.
  • trap -p SIG: prints the current handler, or nothing when no handler is set.
  • EXIT reset: removing an EXIT trap before the end stops its cleanup line.
  • Reinstall after reset: a new trap command after a reset installs a fresh handler.

In this example, the first handler prints and resets itself. The listing after it is empty. A new handler is then installed, the second signal prints its line, and the final listing shows the new handler.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What is the difference between trap '' USR1 and trap - USR1?