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.
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