简体   繁体   中英

Ping from bash-script unknown host

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?

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM