BASH

Find and Kill Process on Occupied Port

A useful bash snippet for web developers to quickly find and terminate processes occupying a specific network port, resolving common local development conflicts.

#!/bin/bash

PORT=$1

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

# Find the PID listening on the specified port
PID=$(lsof -t -i :$PORT)

if [ -z "$PID" ]; then
    echo "No process found listening on port $PORT."
else
    echo "Process (PID: $PID) is listening on port $PORT."
    read -p "Do you want to kill this process? (y/N): " CONFIRM

    if [[ "$CONFIRM" =~ ^[yY]$ ]]; then
        kill -9 $PID
        if [ $? -eq 0 ]; then
            echo "Process $PID killed successfully."
        else
            echo "Failed to kill process $PID." >&2
            exit 1
        fi
    else
        echo "Operation cancelled."
    fi
fi
How it works: This script helps web developers manage port conflicts during local development. It takes a port number as an argument, then uses `lsof -t -i :$PORT` to find the Process ID (PID) currently listening on that port. If a process is found, it prompts the user for confirmation before forcefully terminating the process using `kill -9`, making it easy to free up an occupied port for a new server or application.

Need help integrating this into your project?

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

Hire DigitalCodeLabs