Write a bash script using strict mode (set -euo pipefail) and trap-based error handling for robust automation

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

Steps

  1. Start every script with the strict mode header: #!/usr/bin/env bash followed by set -euo pipefail on the next line.
  2. -e exits on any command returning a non-zero status; -u treats unset variable references as errors; -o pipefail makes pipeline failures propagate the non-zero exit of any failed segment.
  3. Install an ERR trap to log failures with context: trap 'echo "Error on line $LINENO: $BASH_COMMAND" >&2' ERR
  4. Install an EXIT trap for cleanup that must run regardless: trap 'rm -f /tmp/myscript.lock' EXIT
  5. Selectively disable strict mode for known-failing commands using: set +e; some_command_that_may_fail; set -e

Known gotchas

Related routes

Write a robust zsh script with arrays, associative arrays, and strict error handling for system administration tasks
zsh.sourceforge.io · 5 steps · unrated
register bash trap EXIT handlers to reliably clean up temp files and background processes regardless of how a script terminates
gnu.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