BASH Script to Compute the Average Ping to a Domain


The following BASH script uses the ping command and computes the average PING to a domain via awk text processing.

1
2
3
4
5
6
7
8
#!/bin/bash
 
if [[ -z $1 ]]; then
    echo Usage: $0 domain
    exit 1
fi
 
ping -c 3 $1 | head -4 | tail -3 | awk 'BEGIN{a=0;c=0} {a+=substr($8,6);c+=1} END{print(a)/c;}'
#!/bin/bash

if [[ -z $1 ]]; then
    echo Usage: $0 domain
    exit 1
fi

ping -c 3 $1 | head -4 | tail -3 | awk 'BEGIN{a=0;c=0} {a+=substr($8,6);c+=1} END{print(a)/c;}'

The ping command we can specify the number of times via -C option:

1
2
3
4
5
6
7
8
PING helloacm.com(XXXX) 56 data bytes
64 bytes from XXXX: icmp_seq=1 ttl=56 time=10.4 ms
64 bytes from XXXX: icmp_seq=2 ttl=56 time=10.6 ms
64 bytes from XXXX: icmp_seq=3 ttl=56 time=10.6 ms
 
--- helloacm.com ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2003ms
rtt min/avg/max/mdev = 10.400/10.592/10.698/0.180 ms
PING helloacm.com(XXXX) 56 data bytes
64 bytes from XXXX: icmp_seq=1 ttl=56 time=10.4 ms
64 bytes from XXXX: icmp_seq=2 ttl=56 time=10.6 ms
64 bytes from XXXX: icmp_seq=3 ttl=56 time=10.6 ms

--- helloacm.com ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2003ms
rtt min/avg/max/mdev = 10.400/10.592/10.698/0.180 ms

We use the head and tail command the get the lines from 2 to 4 and use awk to get the average of the ping/latency time.

BASH Programming/Shell

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
205 words
Last Post: How to Add a ShortCode to Include a PHP File in WordPress?
Next Post: Teaching Kids Programming - Sum of Three Numbers Less than Target

The Permanent URL is: BASH Script to Compute the Average Ping to a Domain

Leave a Reply