Bash: Timer in while loop

8,473

Solution 1

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
else
  echo connected
fi      

Solution 2

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:

#!/bin/bash

while ! ping -c1 "$1" &>/dev/null; [[ "$SECONDS" -lt 50 ]]
        do echo "Ping Fail - `date`"
done
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.

Share:
8,473

Related videos on Youtube

Vladimir P
Author by

Vladimir P

Updated on September 18, 2022

Comments

  • Vladimir P
    Vladimir P over 1 year

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

    #!/bin/sh
    
    while ! ping -c1 $1 &>/dev/null
            do echo "Ping Fail - `date`"
    done
    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?

    • Jeff Schaller
      Jeff Schaller over 5 years
      understanding that the pings may still be failing after 50 seconds...?
    • Vladimir P
      Vladimir P over 5 years
      Yes, this is exactly what I mean
    • Rui F Ribeiro
      Rui F Ribeiro over 5 years
      You are dealing with ping timeouts too
  • Vladimir P
    Vladimir P over 5 years
    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