Real-Time Script: Service Monitoring Script (Apache/Nginx)
Objective: Monitor if a service (e.g., nginx) is running, and restart it if it's down.
#!/bin/bash # Use bash shell
while true # Infinite loop; runs
do
if systemctl is-active --quiet nginx # Check if nginx is active (quiet mode hides output)
then
echo "Nginx is running" # Inform user that service is up
else
echo "Nginx is down. Restarting..." # Inform user that service is down
systemctl start nginx # Attempt to restart nginx
fi
sleep 60 # Wait 60 seconds before checking again
done # End of while loop
Line-by-Line Brief Explanation:
• #!/bin/bash: Bash interpreter.
• while true: Loop keeps running indefinitely.
• systemctl is-active --quiet nginx: Checks if nginx is active without showing output.
• then: If the service is active...
• echo: Display a message.
• else: If service is not running...
• systemctl start nginx: Restarts the service.
• sleep 60: Waits 1 minute before the next check.
• done: Loop continues.
コメント