user546482872 user546482872 - 13 days ago 5
Bash Question

How can I use an if else statement to catch the error of using ping6 to ping a URL without IPv6?

I am pinging a series of web URLs using

ping6
. Of course, not all URLs have an IPv6 address so I get the output
unknown host
when I try to ping6 a URL without an IPv6 address. What I would like to do, using an if else statement, is catch this error and echo "This site does not have an IPv6 Address", otherwise send a series of ping6's. Here is what I tried:

if [ (ping6 -c 5 $site) = "unknown host" ]; then
echo "$site does not have an IPv6 Address"
else
-irrelevant code in context of question-
fi


I think the issue in my code is
(ping6 -c 5 $site) = "unknown host"
and this is not working as I intended. What would be a better way of catching this error where the site does not have an IPv6 address. Thanks for your time.

Answer

Write the condition like this:

if [ "$(ping6 -c 5 $site 2>&1)" = "unknown host" ]; then

Because:

  • Use $(...) instead of (...), which is a syntax error here
  • Redirect stderr of ping6 to stdout, so that it gets captured
  • Double-quote $(...), so that its result is a single string, otherwise it will be split by spaces, and [ ... ] will fail with the error: too many arguments
Comments