Something went wrong. Try again.
check if a port is being used by any current process
Something went wrong. Try again.
561 B · 26 lines · Created 8mo ago
Shell
1234567891011121314151617181920212223242526#!/usr/bin/env bashset -euo pipefail
if [ $# -ne 1 ]; then echo "Usage: isportfree <port>" >&2 exit 1fi
port="$1"
if ! [[ "$port" =~ ^[0-9]+$ ]]; then echo "Error: port must be a number" >&2 exit 1fi
if lsof -i TCP:"$port" -sTCP:LISTEN -P -n >/dev/null 2>&1; then process=$(lsof -i TCP:"$port" -sTCP:LISTEN -P -n -F pcn 2>/dev/null | awk -F= ' /^p/ { pid=substr($0,2) } /^c/ { cmd=substr($0,2) } /^n/ { printf "%s (PID %s)", cmd, pid; exit } ') echo "Port $port is used by: $process" exit 1else echo "Port $port is free"fi