Poorly written scripts cause more outages than they prevent.
Strict Mode
#!/usr/bin/env bash
set -euo pipefail
Error Handling
cleanup() {
local exit_code=$?
rm -f "$TEMP_FILE"
exit "$exit_code"
}
trap cleanup EXIT ERR
die() { echo "ERROR: $*" >&2; exit 1; }
Structured Logging
log_info() { echo "[$(date)] [INFO] $*"; }
log_error() { echo "[$(date)] [ERROR] $*" >&2; }
Argument Parsing
while [[ $# -gt 0 ]]; do
case "$1" in
-e|--environment) ENVIRONMENT="$2"; shift 2 ;;
-v|--verbose) VERBOSE=true; shift ;;
-h|--help) usage; exit 0 ;;
*) die "Unknown: $1" ;;
esac
done
Improve skills with our Bash eBook collection.