BASH

Monitor and Restart a Linux Process if Down

Create a robust bash script to continuously monitor a critical Linux process by name and automatically restart it if detected as inactive or crashed.

#!/bin/bash

PROCESS_NAME="nginx"
COMMAND_TO_START="sudo systemctl start nginx"

if pgrep -x "$PROCESS_NAME" > /dev/null
then
  echo "$PROCESS_NAME is running."
else
  echo "$PROCESS_NAME is not running. Attempting to start..."
  $COMMAND_TO_START
  if pgrep -x "$PROCESS_NAME" > /dev/null
  then
    echo "$PROCESS_NAME started successfully."
  else
    echo "Failed to start $PROCESS_NAME." >&2
    exit 1
  fi
fi
How it works: This script checks if a process with a given name is currently running. If the process is not found, it attempts to start it using a specified command. This is useful for maintaining the uptime of critical services like web servers or background workers.

Need help integrating this into your project?

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

Hire DigitalCodeLabs