← Back to all snippets
BASH

Monitoring and Restarting a Process Automatically

Implement a Bash script to continuously monitor a specific process (e.g., a web server or background worker) and automatically restart it if it's found to be down.

#!/bin/bash
PROCESS_NAME="nginx" # Or "node", "php-fpm", etc.
RESTART_COMMAND="sudo systemctl restart $PROCESS_NAME"
LOG_FILE="/var/log/process_monitor.log"

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

if ! pgrep -x "$PROCESS_NAME" > /dev/null; then
    echo "$(date): $PROCESS_NAME is not running. Attempting to restart..." | tee -a "$LOG_FILE"
    $RESTART_COMMAND 2>&1 | tee -a "$LOG_FILE"
    if [ $? -eq 0 ]; then
        echo "$(date): $PROCESS_NAME restarted successfully." | tee -a "$LOG_FILE"
    else
        echo "$(date): Failed to restart $PROCESS_NAME." | tee -a "$LOG_FILE"
    fi
else
    echo "$(date): $PROCESS_NAME is running." | tee -a "$LOG_FILE"
fi
How it works: This script checks if a process (specified by PROCESS_NAME) is running using pgrep. If the process is not found, it attempts to restart it using a defined command and logs the action. This is ideal for ensuring critical services like web servers or background workers remain active and resilient.

Need help integrating this into your project?

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

Hire DigitalCodeLabs