BASH

Find and Kill Processes by Name

Efficiently locate and terminate processes by their name or a part of their name using a simple bash script. Ideal for managing background services or unresponsive applications.

#!/bin/bash

# Function to display usage
usage() {
  echo "Usage: $0 <process_name> [signal]"
  echo "  <process_name>: The name or a unique part of the process command line to search for."
  echo "  [signal]: Optional. The signal to send (e.g., SIGTERM, SIGKILL, 9 for KILL). Default is SIGTERM."
  exit 1
}

# Check for required arguments
if [ -z "$1" ]; then
  usage
fi

PROCESS_NAME="$1"
SIGNAL=${2:-"SIGTERM"} # Default to SIGTERM if no signal is provided

echo "Searching for processes matching: '$PROCESS_NAME'"

# Find PIDs using pgrep -f (full command line match)
PIDS=$(pgrep -f "$PROCESS_NAME")

if [ -z "$PIDS" ]; then
  echo "No processes found matching '$PROCESS_NAME'."
else
  echo "Found processes for '$PROCESS_NAME' with PIDs:"
  echo "$PIDS" | while read PID; do
    ps -p "$PID" -o pid,user,etime,command --no-headers
  done
  
  read -rp "Do you want to kill these processes with signal $SIGNAL? (y/N) " CONFIRM
  if [[ "$CONFIRM" =~ ^[yY]$ ]]; then
    echo "Sending $SIGNAL to PIDs: $PIDS"
    kill -s "$SIGNAL" "$PIDS"
    if [ $? -eq 0 ]; then
      echo "Successfully sent $SIGNAL to processes."
    else
      echo "ERROR: Failed to send $SIGNAL to some processes."
      exit 1
    fi
  else
    echo "Operation cancelled by user."
  fi
fi
How it works: This bash script helps manage running processes by allowing you to find and optionally terminate them based on their name. It uses `pgrep -f` to search the full command line of running processes, providing more accurate matches than just the executable name. Before killing, it lists the found processes and asks for user confirmation, preventing accidental shutdowns. It also allows specifying a custom signal, defaulting to `SIGTERM` for graceful termination.

Need help integrating this into your project?

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

Hire DigitalCodeLabs