Skip to content

Instantly share code, notes, and snippets.

@JonTheNiceGuy
Last active May 17, 2023 10:06
Wait for the NIC to be assigned an IP address, then wait for google's DNS to respond, and then sleep for rand(30,600), used like this `wait_for_network.sh && do_something`
#! /bin/bash
# This script checks that the interface is up, and that an internet connection is available
# It is based on code from http://askubuntu.com/questions/3299/how-to-run-cron-job-when-network-is-up
#
# Then it sleeps for a random number of seconds between 30 and 600.
# This is based on code from http://tldp.org/LDP/abs/html/randomvar.html
#
# Collated by @JonTheNiceGuy on 2015-10-15
# Fix from @p1r473 on 2023-05-17 with thanks!
function check_ipaddr
{
# Here we look for an IP(v4|v6) address when doing ip addr
# Note we're filtering out 127.0.0.1 and ::1/128 which are the "localhost" ip addresses
# I'm also removing fe80: which is the "link local" prefix
ip addr | \
grep -v 127.0.0.1 | \
grep -v '::1/128' | \
grep -v 'inet6 fe80:' | \
grep -E "inet [[:digit:]]+\.[[:digit:]]+\.[[:digit:]]+\.[[:digit:]]+|inet6" | \
wc -l
}
function check_google
{
netcat -z -w 5 8.8.8.8 53 && echo 1 || echo 0
}
until [ `check_ipaddr` -ge 1 ]; do
sleep 2
done
until [ `check_google` -eq 1 ]; do
sleep 2
done
sleep $((RANDOM%570+30))
@Konfekt
Copy link

Konfekt commented Jan 25, 2016

how about a timeout after a day say of until .... (for using this as an anacron job).

@p1r473
Copy link

p1r473 commented May 17, 2023

until [ check_ipaddr -gt 1 ]; do

Should be changed to

until [ check_ipaddr -ge 1 ]; do

As its perfectly acceptable to have only 1 IP address.

@JonTheNiceGuy
Copy link
Author

Awesome, great spot, thanks for that @p1r473! Code fixed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment