How to format the output of ping in bash

bashcommand lineping

I am using the following script to cycle through a list of IP addresses and report back on the % of packet loss.

I'd also like to have the IP address printed first, then its % of packet loss. But I can't get the syntax right to make this work.

Ideally, it'd look like:

192.168.99.24  25%
192.168.99.23  0%    
etc...

Here's my script:

#!/bin/bash
HOSTS="192.168.99.24 192.168.99.23"
COUNT=10
SIZE=1400
for myHost in $HOSTS
do

    ping -q -n -s $SIZE -c $COUNT $myHost |  grep "packet loss" | awk '{print $7}'

done

Best Answer

Use

ping -q -n -s $SIZE -c $COUNT $myHost |
    awk -v host=$myhost '/packet loss/ {print host, $7}'

inside the loop.

In case you only want to print the hosts with packet loss use

ping -q -n -s $SIZE -c $COUNT $myHost |
    awk -v host=$myhost '/packet loss/ {if ($7 != "0.0%") print host, $7}'

Side note: grep pattern | awk '{action}' can usually be replaced with the much neater (and slightly faster) awk '/pattern/ {action}'