← Back to all snippets
BASH

Monitor and Restart a Systemd Service

Ensure critical web services remain active. This bash script checks if a specified systemd service is running and restarts it if it's found to be inactive or in a failed state.

#!/bin/bash
SERVICE_NAME=$1

if [ -z "$SERVICE_NAME" ]; then
    echo "Usage: $0 <service_name>"
    echo "Example: $0 nginx"
    exit 1
fi

SERVICE_STATUS=$(systemctl is-active "$SERVICE_NAME")

if [ "$SERVICE_STATUS" == "active" ]; then
    echo "Service '$SERVICE_NAME' is active and running."
else
    echo "Service '$SERVICE_NAME' is $SERVICE_STATUS. Attempting to restart..."
    sudo systemctl restart "$SERVICE_NAME"
    if [ $? -eq 0 ]; then
        echo "Service '$SERVICE_NAME' restarted successfully."
    else
        echo "Error: Failed to restart service '$SERVICE_NAME'."
        exit 1
    fi
fi
How it works: This script helps maintain the uptime of critical services. It takes a service name (e.g., 'nginx', 'apache2') as an argument. It uses `systemctl is-active` to check the current status of the service. If the service is not 'active', the script attempts to restart it using `sudo systemctl restart`, providing feedback on the outcome of the restart attempt.

Need help integrating this into your project?

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

Hire DigitalCodeLabs