-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgetUnusedPort.sh
More file actions
executable file
·32 lines (26 loc) · 851 Bytes
/
getUnusedPort.sh
File metadata and controls
executable file
·32 lines (26 loc) · 851 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#!/bin/bash
# pass in a port number, e.g. "getUnusedPort.sh"
# (if none supplied, start at 1000)
# will spit out the first available port
if [ -z $1 ]; then
startPort=1000
else
startPort=$1
fi
# echo "starting from '$startPort'"
while :
do
# echo "checking port '$startPort'..."
lsof -i -n -P | grep 127.0.0.1.*LISTEN | sed 's/.*TCP 127.0.0.1:\([0-9]*\) .*/\1/' | grep "^${startPort}$" > /dev/null 2>&1
if [ $? -eq 1 ]; then
echo $startPort
exit 0
else
# port is in use; keep looking
:
fi
startPort=$(($startPort+1))
done
# lsof -i -n -P | grep 127.0.0.1.*LISTEN | sed 's/.*TCP 127.0.0.1:\([0-9]*\) .*/\1/' | xargs printf "%05d\n" | sort | uniq
# list of all ports currently in use; zeropadded to 5 digits
# lsof -i -n -P | grep 127.0.0.1.*LISTEN | sed 's/.*TCP 127.0.0.1:\([0-9]*\) .*/\1/' | xargs printf "%05d\n" | sort | uniq