Interview Prep/Shell Scripting/Scenarios: health checks, monitoring and alerts

Alert when any systemd unit on a host is in a failed state.

BeginnerScenarioScenarios: health checks, monitoring and alerts
Answer

Situation read → systemd already tracks failed units; just query it.

What I'd do →

mapfile -t failed < <(systemctl list-units --state=failed --no-legend --plain | awk '{print $1}')
if (( ${#failed[@]} )); then
  echo "CRIT failed units: ${failed[*]}"
  for u in "${failed[@]}"; do journalctl -u "$u" -n 5 --no-pager; done
  exit 2
fi
echo "OK no failed units"
  1. systemctl is-system-running returns degraded when any unit failed, a quick one-word check.
  2. After fixing, systemctl reset-failed clears the state.

Why → Failed oneshot units (backups, cert renewals) are easy to miss because nothing restarts them.

Interview tip → Mention systemctl is-system-running for a single status word.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Scenarios: health checks, monitoring and alerts