idan357
idan357

Reputation: 367

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?

Upvotes: 0

Views: 2887

Answers (2)

Pavlo Hrybok
Pavlo Hrybok

Reputation: 68

You can use this linux utility: https://linux.die.net/man/1/timeout
And your oneliner would be something like this:

timeout 50 bash -c "while true; do if ping -c1 -i1 8.8.8.8 &>/dev/null; then echo "up"; break; fi; done"

Upvotes: 3

iamauser
iamauser

Reputation: 11479

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

Upvotes: 1

Related Questions