Created
April 4, 2017 17:54
-
-
Save rzane/6ef5d43c6d97db430daeebe75aff0d0d to your computer and use it in GitHub Desktop.
Wait for a port to become available (useful for docker-compose)
This file contains 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/bash | |
if [ "$#" -lt 2 ]; then | |
echo "Usage: wait-for-it [host] [port] [timeout(optional)]" | |
exit 1 | |
fi | |
host="$1" | |
port="$2" | |
timeout="${3:-0}" | |
waited=0 | |
delay=2 | |
function try () { | |
if type gtimeout > /dev/null 2>&1; then | |
gtimeout 1 bash -c "$1" | |
else | |
timeout 1 bash -c "$1" | |
fi | |
} | |
until try "> /dev/tcp/$host/$port 2> /dev/null"; do | |
if [ "$timeout" -gt 0 ] && [ "$waited" -ge "$timeout" ]; then | |
echo "Failed to connect to $host:$port after ${waited}s. Giving up." | |
exit 1 | |
fi | |
echo "Waiting for $host:$port... ${waited}s" | |
sleep "$delay" | |
waited=$(($waited + $delay)) | |
done | |
echo "$host:$port is available after ${waited}s" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment