Reputation: 189
I have a file full of hostnames - one in each line. Now I'd like to check if these hostnames exist (and eventually delete them from the file if not). I already fail at the first part:
#!/bin/bash
while read host; do
ping -c1 "$host"
done <hosts
Only gives me
ping: unknown host google.com
(put google.com in the file for testing) I also tried removing the quotes - no effect. However when running the command from a terminal that's what I get:
$ ping -c1 "google.com"
PING google.com (173.194.112.100) 56(84) bytes of data.
...
What's the issue here?
Upvotes: 0
Views: 1791
Reputation: 11
I was trying to do the same thing and I ended up with this script which you may find nice and useful. Still working on the part to try and recognize the "ping: unknown host hostname.co.hk" but that's okay.
#!/bin/bash
cat list | while read domains; do
reply=$(ping -c 1 $domains| grep -E '(from)' | wc -l)
if [ $reply == 1 ]; then
DOMAIN=$(ping -c 1 $domains |grep 64 |awk '{print$4}')
IP=$(ping -c 1 $domains | grep -E -o "([0-9]{1,3}[\.]){3}[0-9]{1,3}" | head -1)
echo "$domains -> $DOMAIN -> $IP" >> ping.log;echo "$domains -> $DOMAIN -> $IP"
else
echo "-----------------ping failed, verify domain name"
fi
done
cat ping.log
Upvotes: 1
Reputation: 18409
Most likely your hosts
file is in DOS line endings format (CR-LF line endings), so read
fills variable with google.com\r
.
Simplest way would be to convert file to UNIX line endings with dos2unix hosts
.
Upvotes: 1