Skip to content

Instantly share code, notes, and snippets.

@steinnes

steinnes/usage.md

Last active Nov 2, 2018
Embed
What would you like to do?
A shellscript which hangs for up to 30 seconds while waiting for a port to become accessible.

A simple way to test this is to run wait_for_port.sh against localhost on a random unused port:

$ .ci/wait_for_port.sh localhost 12345
.....

Then in another shell, listen on that port:

$ nc -l 12345

... and watch how wait_for_port.sh exits beautifully in the first shell:

$ .ci/wait_for_port.sh localhost 12345
................Connection to localhost port 12345 [tcp/italk] succeeded!
OK

This can be quite handy for example when orchestrating CI :-)

#!/bin/bash
RETRIES=30
SUCCESS=1
TRY=0
HOST=$1
PORT=$2
if [ -z "$HOST" -o -z "$PORT" ]
then
echo "Usage: wait_for_port.sh <host> <port>"
exit 1
fi
while [ $SUCCESS -eq 1 -a $TRY -le $RETRIES ]
do
nc -z -w 1 $HOST $PORT 2>&1 > /dev/null
let SUCCESS=$?
if [ $SUCCESS -eq 0 ]
then
echo OK
exit 0
else
let TRY=$TRY+1
sleep 1
fi
printf '.'
done
echo Failure in $RETRIES tries
exit 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment