BASH

Identifying and Terminating Processes Using a Specific Port

Quickly resolve 'address already in use' errors by finding which process occupies a given TCP port and how to gracefully or forcefully terminate it using `lsof` and `kill`.

#!/bin/bash

# Usage: ./kill_port.sh <port_number>

PORT="$1"

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

# Find the Process ID (PID) using lsof
PID=$(lsof -t -i :"$PORT")

if [ -z "$PID" ]; then
  echo "No process found running on port $PORT."
else
  echo "Process $PID is running on port $PORT."
  read -p "Do you want to kill this process? (y/N): " -n 1 -r
  echo # (optional) move to a new line
  if [[ $REPLY =~ ^[Yy]$ ]]; then
    echo "Killing process $PID..."
    kill -9 "$PID" # Use kill -9 for forceful termination
    if [ $? -eq 0 ]; then
      echo "Process $PID killed successfully."
    else
      echo "Failed to kill process $PID." >&2
    fi
  else
    echo "Process $PID was not killed."
  fi
fi
How it works: This bash script helps developers resolve common 'address already in use' issues by identifying and optionally terminating processes listening on a specific TCP port. It uses `lsof -t -i :<PORT>` to find the Process ID (PID) associated with the given port. If a process is found, it prompts the user for confirmation before using `kill -9` for a forceful termination. This is a crucial utility for managing local development environments.

Need help integrating this into your project?

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

Hire DigitalCodeLabs