Error Handling in Bash
Overview
Bash error handling is explicit and must be designed carefully to avoid silent failures in production automation.
Defensive Controls
set -euo pipefailtraphandlers for cleanup and diagnostics- Exit code checks after critical commands
- Structured stderr logging
flowchart TD
A[Run Command] --> B{Exit code 0?}
B -->|Yes| C[Continue]
B -->|No| D[Log Error]
D --> E[Cleanup]
E --> F[Exit Non-Zero]
Practical Example
#!/usr/bin/env bash
set -euo pipefail
trap 'echo "Error on line $LINENO" >&2' ERR
cp config.yaml /etc/myapp/config.yaml
systemctl restart myapp
Production Example
A deployment script should fail fast on migration errors and stop rollout before traffic switching.
Common Pitfalls
- Assuming
set -ehandles every failure scenario - Ignoring subshell and pipeline error behavior
- Missing cleanup handlers for temporary files
Key Takeaways
- Bash reliability depends on explicit failure control.
trapand exit-code checks improve diagnosability.- Fail-fast behavior protects production rollouts.