BASH
Check if a Specific Network Port is Already in Use
Verify if a particular TCP port is currently open and actively listening on the system, preventing conflicts when starting new services.
#!/bin/bash
# Configuration
TARGET_PORT="8080" # The port number to check
# Function to check port availability
check_port() {
local port=$1
# Check using lsof (preferred as it also shows process ID)
if command -v lsof &> /dev/null; then
if lsof -i :"$port" &> /dev/null; then
echo "Port $port is IN USE by PID $(lsof -t -i :"$port")"
return 0 # Port is in use
else
echo "Port $port is FREE (lsof)."
return 1 # Port is free
fi
# Fallback to netstat if lsof is not available
elif command -v netstat &> /dev/null; then
if netstat -tulnp | grep -q ":$port "; then
echo "Port $port is IN USE (netstat)."
return 0 # Port is in use
else
echo "Port $port is FREE (netstat)."
return 1 # Port is free
fi
else
echo "Error: Neither 'lsof' nor 'netstat' found. Cannot check port."
exit 1
fi
}
# Main execution
if [ -z "$TARGET_PORT" ]; then
echo "Error: No port specified. Usage: $0 <port_number>"
exit 1
fi
if check_port "$TARGET_PORT"; then
echo "Action needed: Port $TARGET_PORT is occupied."
# You could add logic here, e.g., kill process, suggest different port
else
echo "Action: Port $TARGET_PORT is available for use."
fi
How it works: This script provides a robust way to determine if a specific TCP port is currently being used by another process on the system. It first attempts to use `lsof -i :PORT`, which is often preferred as it can also identify the Process ID (PID) occupying the port. If `lsof` is not available, it falls back to `netstat -tulnp | grep :PORT`. This is essential for web developers to prevent port conflicts when starting development servers, databases, or other services that require specific network ports.