BASH

Find and Kill Process Using a Specific Port

Prevent 'address already in use' errors by identifying and optionally terminating processes listening on a specified TCP port using this interactive Bash script.

#!/bin/bash

PORT="$1"

# Check if a port number was provided
if [ -z "$PORT" ]; then
    echo "Usage: $0 <port_number>"
    echo "Example: $0 3000"
    exit 1
fi

# Find PIDs using the specified port
PIDS=$(lsof -t -i :"$PORT" 2>/dev/null)

# Check if any processes were found
if [ -z "$PIDS" ]; then
    echo "No process found using port $PORT."
else
    echo "Process(es) using port $PORT: $PIDS"
    read -p "Do you want to kill these processes? (y/N): " choice
    
    # Convert choice to lowercase for case-insensitive comparison
    choice=${choice,,}

    if [[ "$choice" == "y" ]]; then
        # Use 'kill -9' for forceful termination
        kill -9 "$PIDS"
        if [ $? -eq 0 ]; then
            echo "Process(es) $PIDS killed."
        else
            echo "Failed to kill process(es) $PIDS." >&2
            exit 1
        fi
    else
        echo "Processes not killed."
    fi
fi
How it works: This script is designed to help web developers troubleshoot 'address already in use' errors. It takes a port number as an argument and uses `lsof` (list open files) to identify the process IDs (PIDs) that are currently listening on that port. If processes are found, it interactively prompts the user for confirmation before forcefully terminating them using `kill -9`, preventing unintended shutdowns.

Need help integrating this into your project?

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

Hire DigitalCodeLabs