BASH

Check if Process is Running and Restart if Down

A bash script to monitor a specific application process by name and automatically restart it if it's found to be down, ensuring continuous service availability for web applications.

#!/bin/bash

# Check if a process is running and restart it if not.
# Usage: ./check_service.sh "node" "npm start"

PROCESS_NAME="$1"
START_COMMAND="$2"

if [ -z "$PROCESS_NAME" ] || [ -z "$START_COMMAND" ]; then
  echo "Usage: $0 <process_name> <start_command>"
  exit 1
fi

if pgrep -x "$PROCESS_NAME" > /dev/null
then
  echo "$(date): $PROCESS_NAME is running."
else
  echo "$(date): $PROCESS_NAME is not running. Attempting to start..."
  # Execute the start command in the background
  eval "$START_COMMAND" &
  echo "$(date): $PROCESS_NAME started with command: '$START_COMMAND'"
fi
How it works: This script takes a process name and a start command as arguments. It uses `pgrep -x` to efficiently check if a process with the exact given name is currently active. If the process is not found, the script executes the provided start command in the background, ensuring the service is brought back online. This is valuable for simple service monitoring and auto-restart capabilities in production or development environments.

Need help integrating this into your project?

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

Hire DigitalCodeLabs