I have a while loop in my script which waits for the connection get online and then continues.


while ! ping -c1 $1 &>/dev/null
        do echo "Ping Fail - `date`"
echo "Host Found - `date`"

It takes 25 to 45 seconds for the connection to reconnect. I cannot let it wait for any longer than 50 seconds. What would be the best solution to limit the time while loop works?

  • understanding that the pings may still be failing after 50 seconds...? – Jeff Schaller Dec 31 '18 at 14:49
  • Yes, this is exactly what I mean – Vladimir P Dec 31 '18 at 14:51
  • You are dealing with ping timeouts too – Rui F Ribeiro Dec 31 '18 at 15:56

Without a while loop:

# -W 50 = timeout after 50 seconds
# -c 1  = 1 packet to be sent
response="$(ping -W 50 -c 1 "$1" | grep '1 
packets transmitted, 1 received')"

if [ "$response" == '' ] ; then
  echo no response after 50 seconds
  echo connected
  • The problem with this is that until the interface up, the ping exits immediately with No route to host error. It does not wait for 50 sec – Vladimir P Jan 7 at 21:59

A rough cut at it would be to use the bash special variable $SECONDS, which counts the number of seconds since the shell started. I've made three changes to the script:

  1. changed the sh-bang line from /bin/sh to /bin/bash
  2. added a second condition to the while test to compare $SECONDS to 50
  3. quoted $1

The new script:


while ! ping -c1 "$1" &>/dev/null; [[ "$SECONDS" -lt 50 ]]
        do echo "Ping Fail - `date`"
echo "Host Found - `date`"

I would just note that the Host Found statement is potentially misleading in the case of a 50-second timeout. You could compare $SECONDS to 50 after the loop to determine whether the timeout occurred.

This is a rough estimate of 50 seconds, since the loop could be entered with $SECONDS == 49, and then ping could take more than one second to succeed or fail.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.