Skip to content

Instantly share code, notes, and snippets.

@flipsi
Created May 24, 2019 13:28
Show Gist options
  • Save flipsi/74c45948174ef70a01a8a36b4d270a5d to your computer and use it in GitHub Desktop.
Save flipsi/74c45948174ef70a01a8a36b4d270a5d to your computer and use it in GitHub Desktop.
Wait for TCP - Delay command execution until TCP port is ready
#!/bin/sh
set -e
print_usage_and_exit() {
echo "This script performs a given command as soon as a TCP port is open."
echo "Usage: $0 <host> <port> <command>"
exit 2
}
HOST="$1"
if [ -z "$HOST" ]; then print_usage_and_exit; fi
shift
PORT="$1"
if [ -z "$PORT" ]; then print_usage_and_exit; fi
shift
CMD="$@"
if [ -z "$CMD" ]; then print_usage_and_exit; fi
SLEEP_INTERVAL=1
if command -v nc >/dev/null 2>&1; then
METHOD=nc
else
METHOD=telnet
fi
check_connection() {
case $METHOD in
nc )
nc -z "$HOST" "$PORT"
;;
telnet )
echo exit | telnet "$HOST" "$PORT" >/dev/null 2>&1
;;
esac
}
echo "Checking TCP connection on $HOST:$PORT using $METHOD method."
until check_connection; do
>&2 echo "TCP connection failed. Sleeping..."
sleep $SLEEP_INTERVAL
done
>&2 echo "TCP connection successful. Executing command:"
echo $CMD
exec $CMD
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment