BASH
Check Open Port and Identify Process in Bash
Discover how to use Bash to check if a specific network port is in use and identify the process (PID and name) currently listening on it, useful for debugging port conflicts.
#!/bin/bash
# --- Configuration ---
TARGET_PORT=${1:-8080} # Default to 8080 if no argument provided
# --- Check if lsof is installed ---
if ! command -v lsof &> /dev/null; then
echo "Error: 'lsof' command not found. Please install it (e.g., 'sudo apt install lsof' or 'sudo yum install lsof')." >&2
exit 1
fi
echo "Checking if port $TARGET_PORT is in use..."
# --- Use lsof to find processes listening on the target port ---
# -i : selects by internet address
# -P : suppresses port names conversion (e.g., "http" instead of "80")
# -n : suppresses hostnames conversion
# -s TCP:LISTEN : specifically look for TCP sockets in LISTEN state
LSOF_OUTPUT=$(lsof -iTCP:"$TARGET_PORT" -sTCP:LISTEN -P -n 2>/dev/null)
if [ -z "$LSOF_OUTPUT" ]; then
echo "Port $TARGET_PORT is free."
exit 0
else
echo "Port $TARGET_PORT is in use. Details:"
echo "-----------------------------------"
echo "$LSOF_OUTPUT"
echo "-----------------------------------"
# --- Extract PID and Command for more user-friendly output ---
# Get the header line
HEADER=$(echo "$LSOF_OUTPUT" | head -n 1)
echo ""
echo "Summary:"
echo "CMD PID USER FD TYPE DEVICE SIZE/OFF NODE NAME"
echo "--- --- ---- -- ---- ------ -------- ---- ----"
# Loop through each line of output, skip header
echo "$LSOF_OUTPUT" | tail -n +2 | while read -r line; do
# Extract relevant columns: COMMAND, PID, USER
CMD=$(echo "$line" | awk '{print $1}')
PID=$(echo "$line" | awk '{print $2}')
USER=$(echo "$line" | awk '{print $3}')
PROTOCOL_STATE=$(echo "$line" | awk '{print $NF}') # Last column is typically NAME
# Print formatted summary, showing only lines that are actually LISTENING for the specific port
if [[ "$PROTOCOL_STATE" == *":$TARGET_PORT (LISTEN)"* ]]; then
echo "$CMD $PID $USER" # Only print the first three for a concise view. Full line is above.
fi
done
exit 1 # Indicate that the port is in use
fi
How it works: This script checks if a specified network port is currently being listened on by any process. It uses the `lsof` command, which is invaluable for listing open files and network connections. The script first verifies `lsof`'s presence, then uses it to identify processes in a `LISTEN` state on the target port. If the port is in use, it outputs the `lsof` details and a more concise summary of the process (Command, PID, User) that owns the port, aiding in troubleshooting port conflicts for web applications.