-2

I would like to issue a ping command and store the resulting ms value in a variable.

Sample output from a manual ping command:

Client5c:Source_Code user$ ping 8.8.8.8 -c 3

PING 8.8.8.8 (8.8.8.8): 56 data bytes
64 bytes from 8.8.8.8: icmp_seq=0 ttl=54 time=84.222 ms
64 bytes from 8.8.8.8: icmp_seq=1 ttl=54 time=82.900 ms
64 bytes from 8.8.8.8: icmp_seq=2 ttl=54 time=77.398 ms

My attempt from BASH from borrowed code snippets:

ping_val=`ping 8.8.8.8 -c 5 | grep "time= " | head -2 | tail -1 | awk {'print$2'} | cut -f1 -d:`

..which yields nothing.

Charles Duffy
  • 235,655
  • 34
  • 305
  • 356
wiwinut
  • 65
  • 1
  • 6
  • 3
    `grep | head | tail | awk` is an anti-pattern – William Pursell Mar 08 '20 at 16:35
  • I think it should be $7 and -d= -f2 - – eckes Mar 08 '20 at 16:35
  • 2
    "The value"? There are three of them. Do you want the first, the average...? – Benjamin W. Mar 08 '20 at 16:37
  • Thank you for your good question Benjamin. An average absolutely makes sense. – wiwinut Mar 08 '20 at 16:39
  • Your original title was so broad/vague as to look like a duplicate to [How do I set a variable to the output of a command in bash?](https://stackoverflow.com/questions/4651437/how-do-i-set-a-variable-to-the-output-of-a-command-in-bash). Try to make your title *specific to your individual question*. – Charles Duffy Mar 08 '20 at 16:45
  • 1
    On the other hand, it *is* very close to [extract average time from `ping -c`](https://stackoverflow.com/questions/9634915/extract-average-time-from-ping-c). Indeed, if @WilliamPursell saw fit to migrate his excellent answer over there, I'd probably close it as a duplicate. – Charles Duffy Mar 08 '20 at 16:45

1 Answers1

1

There are almost certainly better ways to get this information, but if you just want to get the average of the output shown above, you could do:

$ awk '$3 ~ /time/ { a+=$4;c++} END{print a/c}' FS== input << EOF
> PING 8.8.8.8 (8.8.8.8): 56 data bytes
> 64 bytes from 8.8.8.8: icmp_seq=0 ttl=54 time=84.222 ms
> 64 bytes from 8.8.8.8: icmp_seq=1 ttl=54 time=82.900 ms
> 64 bytes from 8.8.8.8: icmp_seq=2 ttl=54 time=77.398 ms
> EOF
81.5067
William Pursell
  • 174,418
  • 44
  • 247
  • 279