BASH

Check and Restart System Service with Bash

Implement a Bash script to monitor a critical system service like Nginx or MySQL, automatically restarting it if it's not running to maintain uptime.

#!/bin/bash

SERVICE_NAME="nginx"

# Check if the service is active (running)
if systemctl is-active --quiet "$SERVICE_NAME"; then
    echo "$SERVICE_NAME is running."
else
    echo "$SERVICE_NAME is not running. Attempting to restart..."
    sudo systemctl restart "$SERVICE_NAME"
    if [ $? -eq 0 ]; then
        echo "$SERVICE_NAME restarted successfully."
    else
        echo "Error: Failed to restart $SERVICE_NAME."
    fi
fi
How it works: This script checks the status of a specified system service using `systemctl is-active`. If the service is not active (i.e., not running), it attempts to restart it using `sudo systemctl restart`. This is crucial for maintaining the availability of critical web services like Nginx, Apache, or database servers. It can be scheduled with cron to periodically verify service health.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs