BASH

Find and Kill Process Running on a Specific Port

Quickly identify and terminate any process occupying a specified TCP port, essential for resolving port conflicts during web development server startups.

#!/bin/bash

PORT=$1

if [ -z "$PORT" ]; then
    echo "Usage: $0 <port_number>"
    exit 1
fi

echo "Searching for processes on port $PORT..."

PID=$(lsof -t -i:$PORT)

if [ -z "$PID" ]; then
    echo "No process found running on port $PORT."
else
    echo "Process with PID $PID found on port $PORT. Attempting to kill..."
    kill -9 "$PID"
    if [ $? -eq 0 ]; then
        echo "Process $PID killed successfully."
    else
        echo "Failed to kill process $PID. You might need sudo privileges."
    fi
fi
How it works: This script takes a port number as an argument and uses `lsof` (List Open Files) to find the Process ID (PID) of any application listening on that port. If a process is found, it attempts to forcefully terminate it using `kill -9`. This is extremely useful for web developers who frequently encounter "address already in use" errors when starting local development servers.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs