Last active
April 22, 2023 08:44
-
-
Save 9point6/ace9c7db75dc694d434d to your computer and use it in GitHub Desktop.
Keep retrying SSH connection until success (Useful for waiting for VMs to boot)
This file contains hidden or 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
#!/usr/bin/env bash | |
# Check we've got command line arguments | |
if [ -z "$*" ] ; then | |
echo "Need to specify ssh options" | |
exit 1 | |
fi | |
# Start trying and retrying | |
((count = 100)) | |
while [[ $count -ne 0 ]] ; do | |
ssh $* | |
rc=$? | |
if [[ $rc -eq 0 ]] ; then | |
((count = 1)) | |
fi | |
((count = count - 1)) | |
done | |
# Print a message if we failed | |
if [[ $rc -ne 0 ]] ; then | |
echo "Could not connect to $* after 100 attempts - stopping." | |
fi | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice! You could distinguish connection errors (exit code == 255) from other errors like this:
so that
ssh host false
wouldn't repeat 100 times.