SH

Shell Error Handling

Robust error handling patterns for Shell/Bash scripts

Details

Language / Topic
shellShell/Bash
Category
Error Handling

Rules

balanced
- Use `set -euo pipefail` at the top of every script — `-e` exits on error, `-u` exits on undefined variables, `-o pipefail` catches pipe failures.
- Check command exit codes explicitly with `if ! command; then` rather than relying solely on `set -e` for critical operations.
- Use `|| { echo "error message" >&2; exit 1; }` after commands that must succeed to produce actionable error messages.
- Write all error messages to stderr with `echo "ERROR: $msg" >&2` so they do not contaminate captured stdout output.
- Use `trap 'echo "Error on line $LINENO" >&2' ERR` to log the line number of failures for easier debugging in production scripts.
- Avoid `set -e` inside functions that are expected to return non-zero codes — use explicit `return` and check the return value at the call site.
- Implement a `die() { echo "$*" >&2; exit 1; }` helper and call it consistently for all fatal error paths.