forked from ptitfred/posix-toolbox
/
wait-tcp
executable file
·65 lines (51 loc) · 1020 Bytes
/
wait-tcp
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#!/bin/bash
function help {
echo "Usage: wait-for (-v) port [timeout]"
echo " port is a TCP port number, or the service name (for instance http, ssh)"
echo " timeout is expressed in seconds"
echo " optional (defaulted to 30)"
echo " if <= 0, no timeout"
exit 1
}
if [ $# -eq 0 ]; then
help
fi
VERBOSE=0
if [ $1 = "-v" ]; then
VERBOSE=1
shift 1
fi
PORT=$1
# timeout in seconds
TIMEOUT=30
if [ $# -ge 2 ]; then
TIMEOUT=$2
fi
SLEEP=1s
function now {
date +%s
}
startTime=$(now)
function checkTimeout {
if [ $TIMEOUT -gt 0 ]; then
current=$(now)
elapsed=$(( $current - $startTime ))
if [ $elapsed -ge $TIMEOUT ]; then
echo "Timeout" >&2
exit 2
fi
fi
}
function checkPort {
fuser $PORT/tcp 2>/dev/null | wc -c
}
if [ $(checkPort) = 0 -a $VERBOSE -eq 1 ]; then
echo "Waiting for TCP port $PORT"
fi
while [ $(checkPort) = 0 ]
do
checkTimeout
sleep $SLEEP
done
OWNER=$(fuser $PORT/tcp 2>/dev/null | sed -e 's/^.* \([0-9]*\)$/\1/')
echo "$OWNER"