Handling Signals in Bash with trap: Cleanup and Graceful Shutdown Scripts

Use the Bash trap builtin to clean up temp files, handle Ctrl+C, forward signals to child processes and write scripts that shut down gracefully.

Published November 27, 2026

A shell script that creates temporary files, holds a lock or starts background jobs should clean up after itself, even when someone presses Ctrl+C or a supervisor sends SIGTERM. Bash gives you trap for exactly this. Used well, it turns fragile scripts into reliable ones; used carelessly, it can make scripts impossible to stop.

The concept

trap 'commands' SIGNALS registers commands to run when the shell receives one of the listed signals. Besides real signals, Bash supports pseudo-signals: EXIT (runs whenever the shell exits, for any reason), ERR (runs when a command fails, useful with set -e), DEBUG (before every command) and RETURN (when a function returns).

The EXIT trap is the workhorse. Put cleanup there and it runs on normal exit, on exit after an error, and after a signal handler calls exit. A common subtlety: while Bash is waiting for a foreground child process, it defers running traps until that child finishes. To react immediately, run the child in the background and wait for it, because wait returns as soon as a trapped signal arrives.

What a good trap does

Ctrl+Chandlerexitscript runsmktemp, lockSIGINT / SIGTERMtrap firescleanup()rm temp, kill jobsexit 130/143proper status
A trap turns an interruption into an orderly shutdown.

The standard cleanup pattern

Create resources, register a single cleanup function on EXIT, and convert INT and TERM into exits with the conventional status codes (128 + signal number) so callers can tell the script was interrupted.

#!/usr/bin/env bash
set -euo pipefail

tmpdir=$(mktemp -d)
cleanup() {
  local rc=$?
  rm -rf "$tmpdir"
  echo "cleaned up (exit $rc)" >&2
}
trap cleanup EXIT
trap 'exit 130' INT     # 128 + 2
trap 'exit 143' TERM    # 128 + 15

curl -sSfo "$tmpdir/data.json" https://example.com/data.json
jq '.items | length' "$tmpdir/data.json"

Useful traps

TrapFires whenTypical use
EXITShell exits for any reasonRemove temp files, release locks
INTCtrl+CConvert to exit 130, confirm abort
TERMkill, systemd stop, docker stopGraceful shutdown
HUPTerminal closed, or reload requestRe-read config in long-running scripts
ERRA command returns non-zeroLog line number of the failure
'' (empty)Signal is ignoredProtect a critical section
- (dash)Reset to defaultRestore behaviour after a section

Forwarding signals to children

supervisorbash scriptchild (sleep/worker)SIGTERMtrap: kill -TERM $childchild exitswait returns, exit 143
Forwarding signals from a wrapper script to the real worker.

Practical examples

Forward TERM to a background worker

Run the worker in the background and wait, so the trap fires immediately.

#!/usr/bin/env bash
./worker --serve &
child=$!
trap 'kill -TERM "$child" 2>/dev/null' TERM INT
wait "$child"        # returns early when a trapped signal arrives
wait "$child"        # wait again for the child to actually finish
exit $?

Report where a script failed

ERR trap with line number and command.

set -Eeuo pipefail
trap 'echo "error on line $LINENO: $BASH_COMMAND" >&2' ERR

Make a section uninterruptible

Ignore INT while writing, then restore the default.

trap '' INT
mv "$tmpfile" /etc/myapp/config.json     # atomic replace, do not interrupt
trap - INT

Common mistakes

  • Trapping INT and TERM without exiting, creating a script you can only stop with kill -9.
  • Running the main job in the foreground and wondering why the trap only fires after it finishes.
  • Registering several traps on EXIT in different places; each trap call replaces the previous one for that signal.
  • Using single quotes vs double quotes incorrectly: double quotes expand variables when the trap is set, not when it fires.
  • Trying to trap KILL or STOP, which is impossible.

Key takeaways

  • trap cleanup EXIT is the simplest way to guarantee cleanup.
  • Convert INT/TERM to exit 130/143 so callers see an interrupted status.
  • Background the child and wait to make traps responsive and to forward signals.
  • ERR plus set -E gives you useful failure locations.

FAQ

How do I list current traps?

Run trap -p in the shell to print every registered trap.

Does the EXIT trap run on kill -9?

No. SIGKILL terminates the shell immediately without running any trap.

Are traps inherited by subshells?

Traps for caught signals are reset in subshells and child processes; ignored signals stay ignored. Use set -E to inherit ERR traps into functions and subshells.

More Linux articles