ip=$(ping -c 1 $i 2>&1 | grep -m 1 -Eo '([0-9]+\.){3}[0-9]+')|
if ping -c 1 $i > /dev/null 2>&1|
then
can be reduced to
ip=$(ping -q -o -c 1 "$i" 2>&1 | grep -m 1 -Eo '([0-9]+\.){3}[0-9]+')
if [ ! -z "$ip" ]
then
since $ip will either be null ("") or the ipaddr, so if ping -c 1 $i > /dev/null 2>&1 is superfluous
however, you should be aware that returning an ipaddr is not quite the same as the host being 'pingable', see below - the host is NOT PINGABLE (100% packet loss), the exit status of 2 also indicative of same.
not all hosts are pingable for a variety of reasons.
The ipaddress will (typically) have been resolved via DNS without ever actually 'pinging' the host itself.
all of the above may not matter in your case , am merely sharing for your informaton ....
An non ZERO exit status of the ping would indicate the host is not known or unreachable or does not respond to ping requests.
cat danielshell1.sh
#!/usr/local/bin/bash
prtqueue=$1
for host in $(cat $prtqueue)
do
ping -q -o -c 1 $host > /tmp/$host.log 2>&1
if [ $? == 0 ]
then
: # the colon is a NOOP command in bash shell
# echo "$host, IP: $( head -1 /tmp/$host.log | awk -F'[()]' '/\([0-9].*\)/{print $2}' ) is pingable"
else
ip=$(head -1 /tmp/$host.log | awk -F'[()]' '/\([0-9].*\)/{print $2}' )
echo "$host is not pingable, REASON: ${ip:+'host does not respond to ping requests'} $(tail -1 /tmp/$host.log )"
fi
rm /tmp/$host.log
done
#
# test run
#
./danielshell1.sh hosts
local1host is not pingable, REASON: ping: cannot resolve local1host: Unknown host
zzzz.bt is not pingable, REASON: ping: cannot resolve zzzz.bt: Unknown host
bac.com is not pingable, REASON: host does not respond to ping requests 1 packets transmitted, 0 packets received, 100.0% packet loss
bt.co.uk is not pingable, REASON: host does not respond to ping requests 1 packets transmitted, 0 packets received, 100.0% packet loss
Consider using dig instead of nslookup. There are many reasons, but the most germane here is that I think the following would give you only the output you want and no need to post process it.
Sure, a "real-life example" for one of the customers I'm supporting:
For WAN - both dig and nslookup work fine, for LAN - dig is pretty much useless (in this particular case). Of course there is a possibility, that it may be specific DNS server configuration, nevertheless...
Cheers!