Bash trap & Signal Handler Builder

Quick Answer

Select signals (EXIT, ERR, INT, TERM) and cleanup actions, then copy the generated trap block into your script header.

How to use the Bash trap & Signal Handler Builder

  1. 1Select the signals you want to trap in panel 01.
  2. 2Choose cleanup actions (temp files, lock files, background jobs) in panel 02.
  3. 3Toggle per-signal vs. combined handler style and the set -euo pipefail header in panel 03.
  4. 4Copy the trap block only, or the full script header, from panel 04.
  5. 5Paste into your script immediately after the shebang and set -euo pipefail line.

Run this script on a real Linux server

Get $200 free credit — DigitalOcean

Get $200 Free →

Affiliate link · we earn a commission

Need a domain for your next project?

Register with Namecheap — free WHOIS privacy included

Check Domain Prices →

Affiliate link · we earn a commission

PAID RESOURCE — $9

The Production Bash Toolkit

6 scripts + shared library + 52-page field guide. The production layer the free snippets don't cover.

Get the Toolkit →

Frequently Asked Questions

faq — tool

What is the difference between trap EXIT and trap ERR in bash?

EXIT fires every time the script exits, regardless of why — success, failure, or Ctrl+C. ERR fires only when a command returns a non-zero exit code, and only when set -e is active. For cleanup that must always run, use EXIT. For logging failures at the exact line they occur, use ERR.

faq — tool

Should I use single or double quotes in a bash trap statement?

Single quotes in most cases. With double quotes, variables expand immediately when the trap line is parsed, capturing their value at that moment. With single quotes, expansion happens when the trap fires, which is usually what you want. Exception: if you want to capture the current value of $TMPFILE at trap-definition time, double quotes are correct.

faq — tool

Will trap EXIT run if my script calls exit 1?

Yes. EXIT fires on any exit, including explicit exit 1, set -e failures, and SIGTERM. The only way to prevent a trap from running is to kill the script with SIGKILL (kill -9), which cannot be trapped.

faq — tool

How do I pass the exit code to my trap handler so I can log success vs failure?

Capture $? as the first line inside your handler function: local exit_code=$?. After that point $? reflects the cleanup commands themselves, so capture it immediately on entry.

faq — tool

Does trap work with set -euo pipefail?

Yes, and they complement each other. set -e causes the ERR trap to fire on any non-zero exit code. set -u exits with code 1 on unbound variables, triggering the EXIT trap. set -o pipefail propagates pipe failures through the ERR trap. The combination gives complete coverage.