0

In bash I want to test if there is a DNS entry for a hostname. If there is then I want to do X otherwise do Y.

How can I write this? So far I am thinking the following:

if [[ `ping -c 1 $1 2> /dev/null` ]]; then
   # the hostname was not found
   # perform Y
else
   # the hostname was found
   # perform X
fi;

After writing this I am not certain of whether to use &2> instead of 2>. With different exit codes it might be better for me to just do X when the exit code of the ping command is 0.

How would I put this?

1
  • 1
    If you're checking for a DNS entry, perhaps nslookup or dig would do better than ping. Ping can be unsuccessful for reasons besides DNS (e.g., no route), while nslookup or dig would only be testing DNS (including if the server is up, etc). Commented May 19, 2014 at 0:25

1 Answer 1

4

It should be 2>, not &2>. However, [[ `foo` ]] will capture the output of the command foo and try to evaluate it as a conditional expression. This is not what you want. In order to run a command and test its exit status, just do:

if ping -c 1 "$1" 2> /dev/null; then
   # the hostname was found
   # perform X
else
   # the hostname was not found
   # perform Y
fi

(It's a good idea to put $1 in quotes in case the variable contains any special characters.)

Note that an if test in bash succeeds on an exit status of 0, so you need to swap the Y and X blocks.

If you want to suppress all output from ping, then redirect its stdout as well:

if ping -c 1 "$1" 1>/dev/null 2>/dev/null; then
# ...
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.