check if a port is being used by any current process
isportfree.sh
edited
1#!/usr/bin/env bash
2set -euo pipefail
3
4if [ $# -ne 1 ]; then
5 echo "Usage: isportfree <port>" >&2
6 exit 1
7fi
8
9port="$1"
10
11if ! [[ "$port" =~ ^[0-9]+$ ]]; then
12 echo "Error: port must be a number" >&2
13 exit 1
14fi
15
16if lsof -i TCP:"$port" -sTCP:LISTEN -P -n >/dev/null 2>&1; then
17 process=$(lsof -i TCP:"$port" -sTCP:LISTEN -P -n -F pcn 2>/dev/null | awk -F= '
18 /^p/ { pid=substr($0,2) }
19 /^c/ { cmd=substr($0,2) }
20 /^n/ { printf "%s (PID %s)", cmd, pid; exit }
21 ')
22 echo "Port $port is used by: $process"
23 exit 1
24else
25 echo "Port $port is free"
26fi