2 # Use this script to test if a given TCP host/port are available
6 echoerr() { if [[ $QUIET -ne 1 ]]; then echo "$@" 1>&2; fi }
12 $cmdname host:port [-s] [-t timeout] [-- command args]
13 -h HOST | --host=HOST Host or IP under test
14 -p PORT | --port=PORT TCP port under test
15 Alternatively, you specify the host and port as host:port
16 -s | --strict Only execute subcommand if the test succeeds
17 -q | --quiet Don't output any status messages
18 -t TIMEOUT | --timeout=TIMEOUT
19 Timeout in seconds, zero for no timeout
20 -- COMMAND ARGS Execute command with args after the test finishes
27 if [[ $TIMEOUT -gt 0 ]]; then
28 echoerr "$cmdname: waiting $TIMEOUT seconds for $HOST:$PORT"
30 echoerr "$cmdname: waiting for $HOST:$PORT without a timeout"
35 (echo > /dev/tcp/$HOST/$PORT) >/dev/null 2>&1
37 if [[ $result -eq 0 ]]; then
39 echoerr "$cmdname: $HOST:$PORT is available after $((end_ts - start_ts)) seconds"
49 # In order to support SIGINT during timeout: http://unix.stackexchange.com/a/57692
50 if [[ $QUIET -eq 1 ]]; then
51 timeout $TIMEOUT $0 --quiet --child --host=$HOST --port=$PORT --timeout=$TIMEOUT &
53 timeout $TIMEOUT $0 --child --host=$HOST --port=$PORT --timeout=$TIMEOUT &
56 trap "kill -INT -$PID" INT
59 if [[ $RESULT -ne 0 ]]; then
60 echoerr "$cmdname: timeout occurred after waiting $TIMEOUT seconds for $HOST:$PORT"
89 if [[ $HOST == "" ]]; then break; fi
98 if [[ $PORT == "" ]]; then break; fi
107 if [[ $TIMEOUT == "" ]]; then break; fi
123 echoerr "Unknown argument: $1"
129 if [[ "$HOST" == "" || "$PORT" == "" ]]; then
130 echoerr "Error: you need to provide a host and port to test."
134 TIMEOUT=${TIMEOUT:-15}
139 if [[ $CHILD -gt 0 ]]; then
144 if [[ $TIMEOUT -gt 0 ]]; then
153 if [[ $CLI != "" ]]; then
154 if [[ $RESULT -ne 0 && $STRICT -eq 1 ]]; then
155 echoerr "$cmdname: strict mode, refusing to execute subprocess"