BASH
Monitor and Auto-Restart a System Service
Ensure your critical web services stay online with this bash script that periodically checks a service's status and automatically restarts it if it's found to be inactive.
#!/bin/bash
SERVICE_NAME="nginx"
LOG_FILE="/var/log/service_monitor.log"
if systemctl is-active --quiet "$SERVICE_NAME"; then
echo "$(date +%Y-%m-%d_%H:%M:%S) - $SERVICE_NAME is running." >> "$LOG_FILE"
else
echo "$(date +%Y-%m-%d_%H:%M:%S) - $SERVICE_NAME is down. Attempting restart..." >> "$LOG_FILE"
systemctl restart "$SERVICE_NAME" >> "$LOG_FILE" 2>&1
sleep 5 # Give service time to start
if systemctl is-active --quiet "$SERVICE_NAME"; then
echo "$(date +%Y-%m-%d_%H:%M:%S) - $SERVICE_NAME successfully restarted." >> "$LOG_FILE"
else
echo "$(date +%Y-%m-%d_%H:%M:%S) - Failed to restart $SERVICE_NAME." >> "$LOG_FILE"
# Optional: Add alert mechanism here (e.g., send email)
fi
fi
How it works: This script checks the status of a specified systemd service (e.g., `nginx`). If the service is not active, it attempts to restart it and logs the actions. This is useful for maintaining high availability of web servers or backend processes, and can be scheduled with cron.