Write a script that checks if a list of services is running and restarts any that are not.

BeginnerHands-onBash scripting tasks
Answer
#!/usr/bin/env bash
set -uo pipefail
for svc in nginx docker sshd; do
  if ! systemctl is-active --quiet "$svc"; then
    echo "$(date -Is) $svc is down, restarting" | tee -a /var/log/svc-watch.log
    systemctl restart "$svc" || echo "FAILED to restart $svc" >&2
  fi
done

Key trick → systemctl is-active --quiet returns only an exit code, which is perfect for if. -e is left off deliberately so one failed restart doesn't stop the loop.

All Real-World Interview questions Roadmap: Interview readiness

More on Bash scripting tasks