Skip to content
Advertisement

How to ping in linux until host is known with X seconds timeout?

Im trying to wait for a device to boot up in my code and i dont want to use sleep to wait for him. my problem is that sometimes the device fail to boot and im stuck in a loop when using:

until ping -c1 www.google.com &>/dev/null; do :; done
while true; do ping -c1 www.google.com > /dev/null && break; done

How can i try to ping to the device for X seconds and print “DEAD” or “ALIVE” using one liner?

Advertisement

Answer

You need -W option that keeps ping waiting for a timeout of X seconds.

For Linux (iputils):

$ ping -c1 -W10 <url>

For MacOS X:

$ ping -c1 -t10 <url>

Not a one-liner, but this would wait for 10 seconds before timing out:

if ping -c 1 -W 10 www.google.com 1>/dev/null; then 
    echo Success; 
else 
    echo Failed; 
fi
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement