Created
January 11, 2021 10:08
-
-
Save WhoAteDaCake/d56112f16ce6d767ca3ab971d731ccbb to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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: | |
$cmdname host:port [-t timeout] [-- command args] | |
-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() { | |
command="$*" | |
ip=$(getent hosts "${HOST}" | awk {'print $2'}) | |
for i in $(seq $TIMEOUT) ; do | |
echo "Attempting to connect to $HOST:$PORT - ${i}th time." | |
nc -z "$ip" "$PORT" | |
result=$? | |
if [ $result -eq 0 ] ; then | |
if [ -n "$command" ] ; then | |
exec ${command} | |
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 | |
;; | |
-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 | |
if [ "$HOST" = "" -o "$PORT" = "" ]; then | |
echoerr "Error: you need to provide a host and port to test." | |
usage 2 | |
fi | |
wait_for "$@" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment