BASH

Check and Restart a Linux Service

A robust Bash script to check if a specific systemd service is running and restart it if it's inactive or failed, ensuring service continuity for web applications.

#!/bin/bash

# This script checks the status of a systemd service and restarts it if it's not active.

SERVICE_NAME="nginx.service" # Replace with your target service, e.g., 'apache2.service', 'mysql.service'

echo "Checking status of $SERVICE_NAME..."

if systemctl is-active --quiet "$SERVICE_NAME"; then
    echo "$SERVICE_NAME is running and active."
else
    echo "$SERVICE_NAME is not active or has failed. Attempting to restart..."
    sudo systemctl restart "$SERVICE_NAME"
    if [ $? -eq 0 ]; then
        echo "$SERVICE_NAME restarted successfully."
    else
        echo "Failed to restart $SERVICE_NAME. Please check logs for errors."
        exit 1
    fi
fi

exit 0
How it works: This script helps manage critical services on Linux systems that use systemd. It takes a `SERVICE_NAME` (e.g., `nginx.service`) as input. It then uses `systemctl is-active --quiet` to check if the service is currently running. If the service is not active (i.e., stopped, inactive, or failed), the script attempts to restart it using `sudo systemctl restart`. This is invaluable for maintaining uptime for web servers, databases, or other backend services by automatically recovering from unexpected failures.

Need help integrating this into your project?

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

Hire DigitalCodeLabs