BASH

Monitor and Restart a Background Service

Create a robust bash script to check if a critical web service is running and automatically restart it if inactive, ensuring continuous operation and availability.

#!/bin/bash

SERVICE_NAME="nginx"
LOG_FILE="/var/log/my_service_monitor.log"

if pgrep -x "$SERVICE_NAME" > /dev/null
then
  echo "$(date): $SERVICE_NAME is running." >> "$LOG_FILE"
else
  echo "$(date): $SERVICE_NAME is NOT running. Attempting to start..." >> "$LOG_FILE"
  sudo systemctl start "$SERVICE_NAME" >> "$LOG_FILE" 2>&1
  if pgrep -x "$SERVICE_NAME" > /dev/null
  then
    echo "$(date): $SERVICE_NAME started successfully." >> "$LOG_FILE"
  else
    echo "$(date): Failed to start $SERVICE_NAME." >> "$LOG_FILE"
  fi
fi
How it works: This script checks if a service (e.g., `nginx`) is running using `pgrep`. If the service is not found, it attempts to start it using `systemctl` (which often requires `sudo`) and logs the actions to a specified file. This is useful for simple service monitoring and auto-recovery.

Need help integrating this into your project?

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

Hire DigitalCodeLabs