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.
More on Bash scripting tasks
Write the safe header you start every Bash script with, and explain each part.BeginnerWrite a script that alerts when any filesystem is above 80% usage.BeginnerParse an Nginx access log and print the top 10 client IPs by request count.BeginnerWrite a backup script that tars a directory with a timestamp and keeps only the last 7 backups.IntermediateWrite a health-check loop that polls a URL until it returns 200, with a timeout.IntermediateParse command-line flags `-e <env>`, `-v` (verbose) and `-h` in a Bash script.Intermediate