BASH Script for Sustained Ping Testing

Posted on March 2 2020 under networking, troubleshooting, bash, and linux

pingtest.sh

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#!/bin/bash
if [[ "$1" == "-h" || "$1" == "--help" ]]; then
    echo "Usage: $(basename "$0") <destination> -- program send continuous pings and record the results to pingtest_<destination>.csv"
    exit 0
fi

function ping_test {
    DATE=$(date -uIseconds)
    RESULT=$(ping -qi0.2 -c5 $1 | tail -2)
    TX=$(echo "$RESULT" | head -1 | cut -d" " -f1)
    RX=$(echo "$RESULT" | head -1 | cut -d" " -f4)
    LOSS=$(echo "$RESULT" | head -1 | cut -d" " -f6)
    TIMINGS=$(echo "$RESULT" | tail -1 | cut -d" " -f4 | sed 's/\//,/g')
    AVG=$(echo "$TIMINGS" | cut -d"," -f2)
    echo "$DATE,$TX,$RX,$LOSS,$TIMINGS" >> "pingtest_$1.csv"
    printf "%-25s %10s ms %4s loss\n" "$DATE" "$AVG" "$LOSS"
}

echo "Pinging $1, use Ctrl-C to exit"
if [[ ! -f "pingtest_$1.csv" ]]; then
    echo "timestamp,tx,rx,loss,min,avg,max,mdev" >> "pingtest_$1.csv"
fi
while true; do
    ping_test $1 &
    sleep 1
done