blob: 25258218783c51340f3054b4c08b17912abace6e [file] [log] [blame]
Christopher Lott (cl778h)978dbcf2017-08-23 18:27:19 -04001#!/bin/sh
2# https://github.com/Eficode/wait-for.git
3# MIT License
4
5TIMEOUT=15
6QUIET=0
7
8echoerr() {
9 if [ "$QUIET" -ne 1 ]; then printf "%s\n" "$*" 1>&2; fi
10}
11
12usage() {
13 exitcode="$1"
14 cat << USAGE >&2
15Usage:
16 $cmdname host:port [-t timeout] [-- command args]
17 -q | --quiet Do not output any status messages
18 -t TIMEOUT | --timeout=timeout Timeout in seconds, zero for no timeout
19 -- COMMAND ARGS Execute command with args after the test finishes
20USAGE
21 exit "$exitcode"
22}
23
24wait_for() {
25 command="$*"
Christopher Lott (cl778h)6a4a3492017-10-10 15:54:38 -040026 if [ "$QUIET" -ne 1 ]; then echo "$0: probing host $HOST port $PORT"; fi
Christopher Lott (cl778h)978dbcf2017-08-23 18:27:19 -040027 for i in `seq $TIMEOUT` ; do
28 nc -z "$HOST" "$PORT" > /dev/null 2>&1
29 result=$?
30 if [ $result -eq 0 ] ; then
Christopher Lott (cl778h)6a4a3492017-10-10 15:54:38 -040031 if [ "$QUIET" -ne 1 ]; then echo "$0: operation succeeded on try $i"; fi
Christopher Lott (cl778h)978dbcf2017-08-23 18:27:19 -040032 if [ -n "$command" ] ; then
Christopher Lott (cl778h)6a4a3492017-10-10 15:54:38 -040033 if [ "$QUIET" -ne 1 ]; then echo "$0: exec-ing command $command"; fi
Christopher Lott (cl778h)978dbcf2017-08-23 18:27:19 -040034 exec $command
35 fi
36 exit 0
37 fi
Christopher Lott (cl778h)6a4a3492017-10-10 15:54:38 -040038 if [ "$QUIET" -ne 1 ]; then echo "$0: sleeping after try $i"; fi
Christopher Lott (cl778h)978dbcf2017-08-23 18:27:19 -040039 sleep 1
40 done
Christopher Lott (cl778h)6a4a3492017-10-10 15:54:38 -040041 echo "$0: Operation timed out" >&2
Christopher Lott (cl778h)978dbcf2017-08-23 18:27:19 -040042 exit 1
43}
44
45while [ $# -gt 0 ]
46do
47 case "$1" in
48 *:* )
49 HOST=$(printf "%s\n" "$1"| cut -d : -f 1)
50 PORT=$(printf "%s\n" "$1"| cut -d : -f 2)
51 shift 1
52 ;;
53 -q | --quiet)
54 QUIET=1
55 shift 1
56 ;;
57 -t)
58 TIMEOUT="$2"
59 if [ "$TIMEOUT" = "" ]; then break; fi
60 shift 2
61 ;;
62 --timeout=*)
63 TIMEOUT="${1#*=}"
64 shift 1
65 ;;
66 --)
67 shift
68 break
69 ;;
70 --help)
71 usage 0
72 ;;
73 *)
74 echoerr "Unknown argument: $1"
75 usage 1
76 ;;
77 esac
78done
79
80if [ "$HOST" = "" -o "$PORT" = "" ]; then
81 echoerr "Error: you need to provide a host and port to test."
82 usage 2
83fi
84
85wait_for "$@"