mestihudson
mestihudson

Reputation: 21

Test if name resolv with ping (or better than that)

I have a bash function:

resolv(){
  for name in $*; do
    test 1 -eq $(ping -c 1 -q "$name"|grep '1 packet transmitted'|wc -l) && echo ok || echo fail
  done
}

But if I pass a name that is not defined it returns, always:

ping: unknown host name.that.do.not.resolv
fail

How can I solve this?

Upvotes: 0

Views: 78

Answers (2)

keen
keen

Reputation: 850

Sticking with the assumption you need to use ping (because, for example, of the broken^H^H^Hconfused dns resolution in OSX):

Note that your grep wasn't portable - some pings say "packet" and others say "packets"... within the scope of the ping's I had available, ^PING works though.

For your specific question, you wanted to suppress the error output - so just redirect stderr to /dev/null - if it's sh/bash/similar that'd just be 2>/dev/null

Also added -t1 to reduce the amount of time we might spend on a ping fail/lookup fail...might need to tune to suit.

Broke up the test && || into something more readable (and with more obvious logic direction) since we arent really constrained to a oneliner. :)

#!/bin/sh

resolv(){
  for name in $*; do

    count=$(ping -c 1 -q -t1 "$name" 2>/dev/null |grep '^PING'|wc -l)
    if  [ 1 -eq "$count" ]
     then
        echo ok
    else
        echo fail
    fi
  done
}

resolv google.com
resolv icantclick.org
resolv www.yahoo.com
resolv gofish

Upvotes: 0

Dan Cornilescu
Dan Cornilescu

Reputation: 39814

You could try getent which follows the /etc/nsswitch.conf config:

> getent hosts my_laptop
127.0.0.1       localhost my_laptop
> getent hosts www.google.com
2607:f8b0:400b:80a::1014 www.google.com
> getent hosts name.that.do.not.resolv
>

Upvotes: 1

Related Questions