BASH

Monitor and Restart a System Service

Automatically check if a specified systemd service is active and restart it if it's not, ensuring continuous availability for web applications or databases.

#!/bin/bash

monitor_and_restart_service() {
    if [ -z "$1" ]; then
        echo "Usage: monitor_and_restart_service <service_name>"
        return 1
    fi

    SERVICE_NAME="$1"

    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 systemctl is-active --quiet "$SERVICE_NAME"; then
            echo "$SERVICE_NAME restarted successfully."
        else
            echo "Failed to restart $SERVICE_NAME."
            return 1
        fi
    fi
}

# To use:
# monitor_and_restart_service nginx
# monitor_and_restart_service php-fpm
How it works: This Bash script helps maintain the uptime of critical system services. It accepts a service name (e.g., `nginx`, `mysql`, `php-fpm`) and uses `systemctl is-active` to determine its current status. If the service is found to be inactive, the script attempts to restart it using `sudo systemctl restart`. This is a practical solution for ensuring web application components are always running and automatically recover from failures.

Need help integrating this into your project?

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

Hire DigitalCodeLabs