BASH
Find and Terminate Processes by Name or Port
Learn to locate and gracefully stop running processes, like local development servers, using 'ps', 'grep', 'pgrep', and 'kill' commands in Bash.
#!/bin/bash
# --- Find and kill process by name ---
PROCESS_NAME="node" # Common for Node.js dev servers, or 'php' for PHP built-in server
echo "Looking for processes named '$PROCESS_NAME' (using pgrep -f)..."
# pgrep -f searches the full command line, not just the process name
PID_BY_NAME=$(pgrep -f "$PROCESS_NAME")
if [ -n "$PID_BY_NAME" ]; then
echo "Found PIDs for '$PROCESS_NAME': $PID_BY_NAME"
read -p "Do you want to kill these processes? (y/N): " confirm_kill
if [[ "$confirm_kill" =~ ^[Yy]$ ]]; then
kill "$PID_BY_NAME" # Default is SIGTERM for graceful shutdown
echo "Processes $PID_BY_NAME killed."
else
echo "Kill operation cancelled."
fi
else
echo "No processes found named '$PROCESS_NAME'."
fi
echo "
----------------------------------------"
# --- Find and kill process by port ---
PORT="3000" # Common port for local dev servers (e.g., React, Vue, Node.js apps)
echo "Looking for processes using port $PORT (using lsof)..."
# lsof -t -i :PORT lists the PIDs of processes using the specified port
# Requires 'lsof' to be installed (often available by default or via package manager)
PID_BY_PORT=$(lsof -t -i :$PORT)
if [ -n "$PID_BY_PORT" ]; then
echo "Found PID using port $PORT: $PID_BY_PORT"
read -p "Do you want to kill this process? (y/N): " confirm_kill_port
if [[ "$confirm_kill_port" =~ ^[Yy]$ ]]; then
kill "$PID_BY_PORT"
echo "Process $PID_BY_PORT killed."
else
echo "Kill operation cancelled."
fi
else
echo "No process found using port $PORT."
fi
How it works: This powerful Bash script helps web developers manage running processes, especially local development servers. It first searches for processes by name using `pgrep -f`, which matches against the full command line, making it effective for finding `node` or `php` server instances. After finding potential PIDs, it prompts the user for confirmation before sending a `SIGTERM` signal to gracefully shut them down. The second part of the script uses `lsof` to find processes listening on a specific TCP port, a common scenario when a port is already in use by a forgotten server instance, allowing you to free it up.