Ping The Host Table - UGU Tip
I’m not too keen on yesterdays UGU tip of the day and it doesn’t take much to make it work a chunk better, so I thought I’d whine about it on my blog.
Here’s the original snippet:
grep -v "#" /etc/hosts | awk '{print $1}' | while read host
do
ping -c 1 $host
done
But this has some very fixable caveats. It doesn’t deal with blank lines, it’ll try and ping IPv6 addresses (and too many distros put IPv6 entries in the host table these days - even if you disable the IPv6 options) and it will ignore any lines that have a comment, even if the comment is after the field we want. So I wrote my own version (which I can’t see me ever using)
for host in `awk '! /^#|^$|::/ { print $1 }' /etc/hosts`
do
ping -c 1 $host
done
Mine does deal with blank lines (^$), only drops a comment if it’s at the start of the line (^#) and skips all IPv6 addresses (::). If you want to golf it down some more you can even kill both the loop and iterator variable and use xargs instead. But I’m not that bored.