BASH

Check if a Local Port is Available for Use

Write a Bash script to quickly determine if a specific TCP port is open or in use on your local machine, essential for starting new development services.

#!/bin/bash

# Usage: ./check_port.sh <port_number>

PORT="$1"

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

# Validate if PORT is a number
if ! [[ "$PORT" =~ ^[0-9]+$ ]]; then
  echo "Error: Port number must be an integer." >&2
  exit 1
fi

# Check if the port is in use using lsof (preferred on Linux/macOS) or netstat

if command -v lsof &> /dev/null; then
  # Using lsof: -i :<port> lists network files; -sTCP:LISTEN filters for TCP sockets in LISTEN state.
  if lsof -i :"$PORT" -sTCP:LISTEN &> /dev/null; then
    echo "Port $PORT is IN USE."
    exit 1
  else
    echo "Port $PORT is AVAILABLE."
    exit 0
  fi
elif command -v netstat &> /dev/null; then
  # Using netstat: -t (TCP), -u (UDP), -l (listening), -n (numeric). grep -q suppresses output.
  if netstat -tuln | grep -q ":$PORT\b"; then # \b ensures whole word match for the port
    echo "Port $PORT is IN USE."
    exit 1
  else
    echo "Port $PORT is AVAILABLE."
    exit 0
  fi
else
  echo "Error: Neither 'lsof' nor 'netstat' found. Cannot check port status." >&2
  exit 1
fi
How it works: This script provides a simple yet effective way to check if a specific TCP port is currently being listened on by any process on the local system. It prioritizes `lsof` for its directness, falling back to `netstat` if `lsof` is unavailable. This is an indispensable utility for web developers, allowing them to quickly verify port availability before launching local development servers, APIs, or other services, preventing '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