Created
February 9, 2012 18:19
-
-
Save ptitfred/1781774 to your computer and use it in GitHub Desktop.
Wait for a TCP port to be open
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 | |
function help { | |
echo "Usage: wait-for port [timeout]" | |
echo " port is a TCP port number, or the service name (for instance http, ssh)" | |
echo " timeout is expressed in seconds" | |
echo " optional (defaulted to 30)" | |
echo " if <= 0, no timeout" | |
exit 1 | |
} | |
if [ $# -eq 0 ]; then | |
help | |
fi | |
PORT=$1 | |
# timeout in seconds | |
TIMEOUT=30 | |
if [ $# -ge 2 ]; then | |
TIMEOUT=$2 | |
fi | |
SLEEP=1s | |
function now { | |
date +%s | |
} | |
startTime=$(now) | |
function checkTimeout { | |
if [ $TIMEOUT -gt 0 ]; then | |
current=$(now) | |
elapsed=$(( $current - $startTime )) | |
if [ $elapsed -ge $TIMEOUT ]; then | |
echo "Timeout" | |
exit 2 | |
fi | |
fi | |
} | |
function checkPort { | |
fuser $PORT/tcp 2>/dev/null | wc -c | |
} | |
if [ $(checkPort) = 0 ]; then | |
echo "Waiting for TCP port $PORT" | |
fi | |
while [ $(checkPort) = 0 ] | |
do | |
checkTimeout | |
sleep $SLEEP | |
done | |
OWNER=$(fuser $PORT/tcp 2>/dev/null | sed -e 's/\s*//g') | |
echo "$OWNER" |
Supports timeout in seconds.
Cleaner output.
Inline help if missing args.
Licensed under the DO WHAT THE FUCK YOU WANT WITH THIS License :o)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Blocks until a program has successfully open the choosen TCP port.