Error Handling in Bash

Overview

Bash error handling is explicit and must be designed carefully to avoid silent failures in production automation.

Defensive Controls

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

Key Takeaways