Thursday, April 24, 2014

BASH - customize ping output

Problem is simply: how to get the output of ping command suited to our needs. In this example we will extract average ping time in Bash scripting language.

First let's see output of ping command: ping 192.168.1.1 -c 5 (-c 5 tells to ping command to run five times, else it will run infinitely.)

$ ping 192.168.1.1 -c 5
PING 192.168.1.1 (192.168.1.1) 56(84) bytes of data.
64 bytes from 192.168.1.1: icmp_seq=1 ttl=64 time=2.62 ms
64 bytes from 192.168.1.1: icmp_seq=2 ttl=64 time=0.477 ms
64 bytes from 192.168.1.1: icmp_seq=3 ttl=64 time=0.482 ms
64 bytes from 192.168.1.1: icmp_seq=4 ttl=64 time=0.482 ms
64 bytes from 192.168.1.1: icmp_seq=5 ttl=64 time=0.487 ms

--- 192.168.1.1 ping statistics ---
5 packets transmitted, 5 received, 0% packet loss, time 4000ms
rtt min/avg/max/mdev = 0.477/0.911/2.629/0.859 ms

Average ping time is in last line. Use tail -1 to extract only last line. 

$ ping 192.168.1.1 -c 5|tail -1
rtt min/avg/max/mdev = 0.477/0.911/2.629/0.859 ms

Then extract values, count 'arguments' in this line separated by space: 'rtt' is the first, 'min/avg/max/mdev' 2nd, '=' 3rd, '0.477/0.911/2.629/0.859' 4th and 'ms' 5th. 

$ ping 192.168.1.1 -c 5|tail -1|awk '{print $4}'
0.477/0.911/2.629/0.859

and finally, from this output of four '/' separated values, take the second value: this is done by cut command: 

$ ping 192.168.1.1 -c 5|tail -1|awk '{print $4}'|cut -d '/' -f 2
0.911

and this is the value that we are looking for... 

No comments:

Post a Comment