BASH
Find and Stop a Process by Port Number
A simple Bash script to identify and terminate any process currently listening on a specified TCP port, resolving port conflicts efficiently.
#!/bin/bash
PORT_NUMBER=$1
if [ -z "$PORT_NUMBER" ]; then
echo "Usage: $0 <port_number>
"
exit 1
fi
echo "Searching for processes listening on port $PORT_NUMBER...
"
# Use lsof to find the PID listening on the specified port
# -t option outputs only PIDs, -i :port_number filters by port
PID=$(lsof -t -i :"$PORT_NUMBER" 2>/dev/null)
if [ -z "$PID" ]; then
echo "No process found listening on port $PORT_NUMBER.
"
else
echo "Process with PID $PID found on port $PORT_NUMBER.
"
read -p "Do you want to kill this process? (y/N): " CONFIRM
if [[ "$CONFIRM" =~ ^[yY]$ ]]; then
kill "$PID"
echo "Process $PID killed.
"
else
echo "Operation cancelled.
"
fi
fi
How it works: This script helps resolve port conflicts, a common issue in development environments. It takes a port number as an argument and uses `lsof -t -i :<port>` to find the Process ID (PID) that is currently listening on that port. If a process is found, it prompts the user for confirmation before sending a `kill` signal to terminate the process, freeing up the port for other applications.