Reputation: 751
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?
Upvotes: 0
Views: 86
Reputation: 57470
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
# ...
Upvotes: 4