7

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
7

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

  • you can simplify the quoting a bit: awk -v host=$myhost '/packet loss/ {print host, $7}' – glenn jackman Aug 23 '12 at 23:42
  • @glennjackman good point, didn't think about that. – nohillside Aug 24 '12 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 Aug 24 '12 at 20:02
  • @ITDude: just precede the print with if($7 != "0%") – Thor Aug 25 '12 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 Aug 28 '12 at 22:59

You must log in to answer this question.

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