Wait for Network Interface Before Executing Command
I've tested this on a board which is configured via DHCP.
The assumption is that if a default gateway exists on a specific interface (in this case eth0
), then this is due to the fact that the board has gotten assigned an IP (and thus the default gateway) by the DHCP server, which implies that networking is up and running.
My issue was that for me networking is considered to be up as soon as machines in the LAN/intranet can be accessed, even if there exists no internet connectivity (ie 8.8.8.8 or www.google.com is not accessible). I also don't want to ping specific IPs or domain names in the intranet because I don't want to make assumptions about the subnet or which devices will definitely be up and what their IP or domain name is.
while ! ip route | grep -oP 'default via .+ dev eth0'; do
echo "interface not up, will try again in 1 second";
sleep 1;
done
This command should wait until it can contact google or it has tried 50 times:
for i in {1..50}; do ping -c1 www.google.com &> /dev/null && break; done
The for i in {1..50}
loops 50 times or until a break
is executed. The ping -c1 www.google.com
sends 1 ping packet to google, and &> /dev/null
redirects all the output to null, so nothing is outputed. && break
executes break only if the previous command finished successfully, so the loop will end when ping
is successful.