BASH

Find and Kill Process by Port

Quickly identify and terminate any process listening on a specific TCP port using `lsof` and `kill`, resolving common port conflicts during development.

#!/bin/bash

PORT=$1

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

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

if [ -n "$PID" ]; then
  echo "Process (PID: $PID) is listening on port $PORT. Killing it..."
  kill -9 "$PID"
  echo "Process killed."
else
  echo "No process found listening on port $PORT."
fi
How it works: This script takes a port number as an argument. It uses `lsof -t -i :$PORT` to find the Process ID (PID) of any process listening on that port. If a PID is found, it uses `kill -9` to forcefully terminate the process, helping resolve "address already in use" errors.

Need help integrating this into your project?

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

Hire DigitalCodeLabs