wait-for/wait-for

85 lines
1.4 KiB
Plaintext
Raw Normal View History

2017-05-02 19:13:27 +02:00
#!/bin/sh
TIMEOUT=15
QUIET=0
echoerr() {
if [ "$QUIET" -ne 1 ]; then printf "%s\n" "$*" 1>&2; fi
}
usage() {
exitcode="$1"
cat << USAGE >&2
Usage:
$0 host:port [-t timeout] [-- command args]
2017-05-02 19:13:27 +02:00
-q | --quiet Do not output any status messages
-t TIMEOUT | --timeout=timeout Timeout in seconds, zero for no timeout
-- COMMAND ARGS Execute command with args after the test finishes
USAGE
exit "$exitcode"
}
wait_for() {
for _ in $(seq $TIMEOUT) ; do
2017-05-03 10:52:29 +02:00
nc -z "$HOST" "$PORT" > /dev/null 2>&1
2020-02-03 16:08:25 +01:00
2017-05-02 19:13:27 +02:00
result=$?
if [ $result -eq 0 ] ; then
2017-08-25 02:50:42 +02:00
if [ $# -gt 0 ] ; then
exec "$@"
2017-05-02 19:13:27 +02:00
fi
exit 0
fi
sleep 1
done
echo "Operation timed out" >&2
exit 1
}
while [ $# -gt 0 ]
do
case "$1" in
*:* )
HOST=$(printf "%s\n" "$1"| cut -d : -f 1)
PORT=$(printf "%s\n" "$1"| cut -d : -f 2)
shift 1
;;
-q | --quiet)
QUIET=1
shift 1
;;
-t)
TIMEOUT="$2"
if [ "$TIMEOUT" = "" ]; then break; fi
shift 2
;;
--timeout=*)
TIMEOUT="${1#*=}"
shift 1
;;
--)
shift
break
;;
--help)
usage 0
;;
*)
echoerr "Unknown argument: $1"
usage 1
;;
esac
done
2020-02-03 16:08:25 +01:00
if ! [ -x "$(command -v nc)" ]; then
echoerr "Error: netcat is required for wait-for to run."
exit 1
fi
if [ "$HOST" = "" ] || [ "$PORT" = "" ]; then
2017-05-02 19:13:27 +02:00
echoerr "Error: you need to provide a host and port to test."
usage 2
fi
wait_for "$@"