Skip to content

Instantly share code, notes, and snippets.

@sarvsav
Created August 4, 2025 15:49
Show Gist options
  • Select an option

  • Save sarvsav/eeb5e44f0405f8a5218617b9bf4f7333 to your computer and use it in GitHub Desktop.

Select an option

Save sarvsav/eeb5e44f0405f8a5218617b9bf4f7333 to your computer and use it in GitHub Desktop.
A script to check whether the process is alive or running
#!/bin/bash
# ==============================================================================
# Script Name: process_checker.sh
# Description: Checks if a specific process is currently running.
# This script uses 'pgrep' for a reliable check and returns a
# clear exit code.
# Usage: ./process_checker.sh <process_name>
#
# Exit Codes:
# 0: The process is running.
# 1: The process is not running.
# 2: Invalid usage (e.g., no process name provided).
# ==============================================================================
# --- Function to display script usage ---
show_usage() {
echo "Usage: $0 <process_name>"
echo "Example: $0 'sshd'"
exit 2
}
# --- Check if a process name argument was provided ---
# $# holds the number of arguments passed to the script.
if [ "$#" -ne 1 ]; then
echo "Error: You must provide a single process name to check."
show_usage
fi
# Store the process name from the first command-line argument.
PROCESS_NAME="$1"
# --- Use pgrep to find the process ---
# 'pgrep' is a more robust tool for finding processes than 'ps | grep'.
# '-x' ensures an exact match of the process name.
# '-c' counts the number of matching processes.
# We redirect standard output and standard error to /dev/null to keep the console clean.
# 'pgrep' returns an exit code of 0 if it finds one or more processes.
# It returns 1 if no processes are found.
if pgrep -x "$PROCESS_NAME" &> /dev/null; then
echo "SUCCESS: The process '$PROCESS_NAME' is running."
exit 0
else
echo "FAILURE: The process '$PROCESS_NAME' is not running."
exit 1
fi
## Legacy methods
# Sending kill -0 <pid>
# or, if [ -e /proc/$PID ]; then
# ....
# fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment