Skip to content

Instantly share code, notes, and snippets.

@dragosboca
Last active April 21, 2016 11:06
Show Gist options
  • Save dragosboca/5221a493aef21097780c90ec2ca79588 to your computer and use it in GitHub Desktop.
Save dragosboca/5221a493aef21097780c90ec2ca79588 to your computer and use it in GitHub Desktop.
#!/bin/bash
trap "echo interrupted && exit 2" INT TERM QUIT
limit=100
op=open
while getopts ":csw:" opt; do
case $opt in
c) op=close
;;
s) silence=1
;;
w) limit=$OPTARG
;;
:) echo "$0: option requires an argument -- '$OPTARG'" >&2
exit 1
;;
*) echo "$0: invalid option -- '$OPTARG'" >&2
exit 1
;;
esac
done
shift $((OPTIND-1))
if [[ $# -lt 2 ]]; then
cat <<EOF
usage: wait-for-port.sh [OPTION]... HOST PORT...
-c wait until the port is closed. Otherwise wait until for opening.
-s silent mode
-w COUNT If number of retrying operation exceeds COUNT exit with exit code 1.
by default, COUNT is 100. Use -1 for unlimited waiting)
EOF
exit 1
fi
host=$1
shift
for port in $@; do
test -z ${silence} && echo -n Wait for TCP ${host}:${port} ${op}...
tries=0
while true; do
if [[ ${limit} -gt 0 && ${tries} -ge ${limit} ]]; then
failed=1
break
fi
timeout --foreground 0.5 bash -c "echo > /dev/tcp/${host}/${port}" &>/dev/null
ret=$?
[ ${op} = close ] && [ ${ret} -ne 0 ] && break
[ ${op} = open ] && [ ${ret} -eq 0 ] && break
sleep 1
((tries++))
done
if [[ -z ${silence} ]]; then
if [[ -z ${failed} ]]; then
echo done
else
echo failed
fi
fi
[[ -n ${failed} ]] && exit 1
done
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment