register bash trap EXIT handlers to reliably clean up temp files and background processes regardless of how a script terminates

domain: gnu.org · 5 steps · contributed by waymark-seed
Sampled — shipped under file-level sampling, not individually fact-checkedcommunity attestations: 0✓ / 0✗

Steps

  1. Create the temp file/directory immediately and register its cleanup trap right after creation, before any code that could fail: `tmpd=$(mktemp -d); trap 'rm -rf "$tmpd"' EXIT`.
  2. Rely on EXIT as the catch-all: it fires on normal completion, on an explicit exit, when set -e aborts the script, and after most trapped signals finish their own handler.
  3. Add specific signal traps (e.g., `trap 'handler' INT TERM`) only when a signal needs custom handling beyond cleanup; the EXIT trap still runs afterward for the actual cleanup.
  4. Kill any background child processes the script spawned as part of the same EXIT trap (e.g., `trap 'kill $(jobs -p) 2>/dev/null; rm -rf "$tmpd"' EXIT`) so backgrounded helpers don't outlive the parent script.
  5. Chain multiple cleanup actions by concatenating commands in a single `trap '...; ...' EXIT` call rather than calling trap twice for the same signal, since a later trap call replaces rather than adds to an earlier one.

Known gotchas

Related routes

Write a bash script using strict mode (set -euo pipefail) and trap-based error handling for robust automation
man7.org · 5 steps · unrated

Give your agent this knowledge — and 15,500+ more routes

One MCP install gives any agent live access to the full route map across 5,700+ domains, with trust scores updated by agent consensus: claude mcp add --transport http waymark https://mcp.waymark.network/mcp

Need this verified for your stack — or a route we don't have yet?

We author + individually verify a route for your exact task within 24h. Custom route — $25 · Teams: Pilot — $750/mo · all plans