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:  25%  0%    

Here's my script:

for myHost in $HOSTS

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


1 Answer 1



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}'

  • you can simplify the quoting a bit: awk -v host=$myhost '/packet loss/ {print host, $7}' Commented Aug 23, 2012 at 23:42
  • @glennjackman good point, didn't think about that.
    – nohillside
    Commented Aug 24, 2012 at 3:22
  • Since this is such a handy dandy script now, how could I add an if/then clause into it that only echoes the output if the packet loss is anything other than 0%
    – IT Dude
    Commented Aug 24, 2012 at 20:02
  • @ITDude: just precede the print with if($7 != "0%")
    – Thor
    Commented Aug 25, 2012 at 7:49
  • Patrix, you rock, that works great. How to incorporate an email sent when/if the packet loss is not 100% ? This assumes that postfix or another MTA is already working correctly...
    – IT Dude
    Commented Aug 28, 2012 at 22:59

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .