Need Terminal command to ping every second, pause and then repeat

bashNetworkpingterminalzsh

I want to find a Terminal command that will provide a timestamped ping every second for a period of time (say 5 minutes) and then pause for another period of time (say 30 minutes) and then repeat that process until I stop it. I will need to let it run for days.

In other words, what I want is sort of a combination of the following 2:

1) ping 8.8.8.8 | while read line; do echo `date` - $line; done
2) ping 8.8.8.8 | while read line; do echo `date` - $line; sleep 1800; done

(1) provides a ping listing every second with a timestamp, while (2) does the same thing but every 30 minutes instead of every second. I can use (1) but it generates way more data than I need. (2) provides the pauses I need but cannot catch the events I'm looking for (which last about 4 seconds, see below).

Although not needed to answer my question, the reason I want this is to deal with an intermittent internet connectivity problem. By using (1) above I have found that most of the time my internet connection is fine, but every couple of days or so there will be periods (lasting hours) during which I get unusually high pings for about 4 seconds, and this repeats every 15 seconds or so. But using (1) to figure that out meant a lot of unnecessary data collection. Also, I have a separate script which will plot the data and there are just way too many data points to plot conveniently since I need to collect for days.

I'm running OS 13.2 on a MacAir M1

Best Answer

while :; do
    ping --apple-time -c $((5*60)) 8.8.8.8
    sleep $((30*60))
    echo # if required to separate the blocks
done

--apple-time obviously is an Apple addition which is quite useful for what you need here, the output would look like

15:50:24.467213 64 bytes from 8.8.8.8: icmp_seq=0 ttl=114 time=2.991 ms
15:50:25.471150 64 bytes from 8.8.8.8: icmp_seq=1 ttl=114 time=1.805 ms
15:50:26.476259 64 bytes from 8.8.8.8: icmp_seq=2 ttl=114 time=1.822 ms
15:50:27.480521 64 bytes from 8.8.8.8: icmp_seq=3 ttl=114 time=1.832 ms
15:50:28.485576 64 bytes from 8.8.8.8: icmp_seq=4 ttl=114 time=1.785 ms

If you just want the timestamp and the ping time, you can use sed to filter out the noise:

$ ping --apple-time -c $((5*60)) 8.8.8.8 | sed -n -E 's/(.*) 64 bytes.*time=(.*) ms/\1 \2/p'
19:11:49.447810 2.928
19:11:50.450692 1.836
19:11:51.455125 1.829

To accomplish the same without relying on Apple-specific options, you can also just take your second command and put the sleep outside of the while read line loop:

while :; do
    ping -c $((5*60)) 8.8.8.8 | while read line; do echo $(date): "$line"; done
    sleep $((30*60))
    echo # if required to separate the blocks
done

or, again without the noise

while :; do
    ping -c $((5*60)) 8.8.8.8 | while read line; do 
        echo $(date): $(sed -n -E 's/.*time=(.*) ms/\1/p' <<<$line)
    done
    sleep $((30*60))
    echo # if required to separate the blocks
done