BASH
Check for Open Ports and Kill Processes
Learn how to use a bash script to check if a specific port is in use and, if desired, automatically identify and terminate the process occupying that port.
#!/bin/bash
PORT=$1
if [ -z "$PORT" ]; then
echo "Usage: $0 <port_number>"
exit 1
fi
PID=$(lsof -t -i:$PORT)
if [ -z "$PID" ]; then
echo "Port $PORT is free."
else
echo "Port $PORT is occupied by PID $PID."
read -p "Do you want to kill this process? (y/N): " choice
if [[ "$choice" =~ ^[Yy]$ ]]; then
kill -9 "$PID"
echo "Process $PID killed."
else
echo "Process not killed."
fi
fi
How it works: This script takes a port number as an argument, uses `lsof` to determine if that port is in use, and identifies the process ID (PID) occupying it. If the port is busy, it prompts the user to confirm whether they want to terminate the process. This is particularly useful for web developers who often encounter "Address already in use" errors when starting local servers.