Bash Error Handling and Best Practices

Production scripts need proper error handling.

set -euo pipefail

Bash
#!/bin/bash
set -euo pipefail
# -e: Exit on any command failure
# -u: Treat unset variables as errors
# -o pipefail: A pipeline fails if ANY command fails

trap for Cleanup

Bash
TEMP_FILE=$(mktemp)
cleanup() { rm -f "$TEMP_FILE"; }
trap cleanup EXIT

Retry with Backoff

Bash
retry() {
    local max_attempts=$1 delay=$2
    shift 2
    for ((i = 1; i <= max_attempts; i++)); do
        if "$@"; then return 0; fi
        sleep "$delay"
        delay=$((delay * 2))
    done
    return 1
}

retry 3 1 curl -f https://api.example.com/health

Defensive Scripting

Bash
# Always quote variables
filename="$1"
if [[ ! -f "$filename" ]]; then
    echo "Error: File '$filename' not found" >&2
    exit 1
fi

# Check required commands
for cmd in curl jq bc; do
    if ! command -v "$cmd" &>/dev/null; then
        echo "Error: Required command '$cmd' not found" >&2
        exit 1
    fi
done

Tips

  • Always start scripts with set -euo pipefail.
  • Use trap cleanup EXIT for resource cleanup.
  • Quote all variables — prevents word splitting and globbing.

🎉 You have completed the Bash course!