Skip to content

Instantly share code, notes, and snippets.

@ptitfred
Created February 9, 2012 18:19
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ptitfred/1781774 to your computer and use it in GitHub Desktop.
Save ptitfred/1781774 to your computer and use it in GitHub Desktop.
Wait for a TCP port to be open
#!/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"
@ptitfred
Copy link
Author

ptitfred commented Feb 9, 2012

Blocks until a program has successfully open the choosen TCP port.

@ptitfred
Copy link
Author

ptitfred commented Feb 9, 2012

Supports timeout in seconds.
Cleaner output.
Inline help if missing args.

@ptitfred
Copy link
Author

ptitfred commented Feb 9, 2012

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