BASH
Check and Kill Process Using a Specific Port
Write a bash script to detect if a given network port is in use and, if so, identify and offer to kill the process occupying it, preventing development server conflicts.
#!/bin/bash
# This script checks if a specified port is in use and offers to kill the process.
# It's useful for web developers to free up ports used by hung development servers.
if [ "$#" -ne 1 ]; then
echo "Usage: $0 <port_number>"
echo "Example: $0 3000"
exit 1
fi
PORT=$1
echo "Checking if port $PORT is in use..."
# Use lsof to find processes listening on the specified port
# -i : selects files by IP address
# -P : inhibits the conversion of port numbers to port names
# -t : produces terse output with process IDs only
PID=$(lsof -i ":$PORT" -t)
if [ -n "$PID" ]; then
echo "Port $PORT is in use by process with PID: $PID"
# Get process name for better user feedback
PROCESS_INFO=$(ps -p "$PID" -o comm=)
echo "Process name: $PROCESS_INFO"
read -rp "Do you want to kill this process (PID: $PID)? (y/N): " response
if [[ "$response" =~ ^[Yy]$ ]]; then
kill "$PID"
if [ $? -eq 0 ]; then
echo "Process $PID (name: $PROCESS_INFO) killed successfully."
else
echo "Failed to kill process $PID."
fi
else
echo "Process $PID was not killed."
fi
else
echo "Port $PORT is not in use."
fi
How it works: This bash script is a handy tool for web developers, especially when dealing with local development servers that might crash or leave ports open. It takes a port number as an argument, uses `lsof` to determine if that port is currently in use, and if so, identifies the process ID (PID) and its name. The script then prompts the user to confirm whether they want to terminate the identified process, helping to quickly free up busy ports.