#!/bin/bash PORT=$1 # Check if a port number was provided if [ -z "$PORT" ]; then echo "Usage: $0 " echo "Example: $0 8080" exit 1 fi # Check if lsof is installed if ! command -v lsof &> /dev/null then echo "Error: 'lsof' command not found. Please install it (e.g., 'sudo apt-get install lsof' or 'brew install lsof')." exit 1 fi echo "Checking if port $PORT is in use..." # Find the PID using the specified port # -t: output process IDs only # -i :PORT: list network files by internet address (port) PID=$(lsof -t -i :"$PORT" 2>/dev/null) if [ -n "$PID" ]; then echo "Port $PORT is in use by process(es) with PID: $PID" read -p "Do you want to kill these processes? (y/N): " response if [[ "$response" =~ ^[yY]$ ]]; then echo "Killing process(es) $PID..." kill -9 "$PID" # -9 sends a SIGKILL signal, ensuring termination if [ $? -eq 0 ]; then echo "Process(es) $PID killed successfully." else echo "Failed to kill process(es) $PID." fi else echo "Processes on port $PORT were not killed." fi else echo "Port $PORT is free. No process found listening on this port." fi