BASH

Check and Restart a Linux Service or Process

A Bash script to verify if a specified process or service is running and, if not, restart it, ensuring continuous application availability.

#!/bin/bash

SERVICE_NAME="nginx" # Or a process name like "my_app_process"
LOG_FILE="/var/log/service_monitor.log"

# Ensure log file exists
mkdir -p "$(dirname "$LOG_FILE")"
touch "$LOG_FILE"

# Check if the service is active (using systemctl for systemd services)
if systemctl is-active --quiet "$SERVICE_NAME"; then
  echo "$(date): $SERVICE_NAME is running." >> "$LOG_FILE"
else
  echo "$(date): $SERVICE_NAME is NOT running. Attempting to restart..." >> "$LOG_FILE"
  if sudo systemctl restart "$SERVICE_NAME"; then
    echo "$(date): $SERVICE_NAME restarted successfully." >> "$LOG_FILE"
  else
    echo "$(date): Failed to restart $SERVICE_NAME." >> "$LOG_FILE"
    # Add alert mechanism here, e.g., email notification
  fi
fi

# Alternative for non-systemd processes:
# if pgrep -x "$SERVICE_NAME" > /dev/null; then
#   echo "$(date): $SERVICE_NAME process is running." >> "$LOG_FILE"
# else
#   echo "$(date): $SERVICE_NAME process is NOT running. You might need to manually start or re-run the application." >> "$LOG_FILE"
# fi
How it works: This script monitors the status of a specified systemd service (e.g., `nginx`). It uses `systemctl is-active` to check if the service is currently running. If the service is found to be inactive, the script attempts to restart it using `sudo systemctl restart`. All actions and timestamps are logged to a specified file, providing a record of service uptime and interventions.

Need help integrating this into your project?

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

Hire DigitalCodeLabs