Count HTTP status codes from an access log and alert if 5xx is more than 5% of requests.

AdvancedHands-onBash scripting tasks
Answer
#!/usr/bin/env bash
set -euo pipefail
LOG=/var/log/nginx/access.log

read -r total errors < <(awk '{t++; if ($9 ~ /^5/) e++} END {print t+0, e+0}' "$LOG")
pct=$(awk -v e="$errors" -v t="$total" 'BEGIN { if (t == 0) print 0; else printf "%.2f", e*100/t }')
echo "total=$total 5xx=$errors pct=$pct%"

if awk -v p="$pct" 'BEGIN { exit !(p > 5) }'; then
  echo "ALERT: 5xx rate $pct% above 5%" >&2
  exit 2
fi

Key trick → Bash only does integer maths, so float comparison goes through awk. exit !(cond) maps true to exit code 0 so it can be used in an if.

All Real-World Interview questions Roadmap: Interview readiness

More on Bash scripting tasks