This question already has an answer here:

I'm trying to compare the result of a command substitution to a string, like this:

if [$(ping $1)=="ping: unknown host localhosts"]
  echo "no";
  echo "yes";

What am I doing wrong here?

marked as duplicate by Gilles bash Jul 29 '17 at 12:47

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.


First, you forgot the space and the quoting. Next, it's an error, so you should catch stderr. Finally localhosts is probably $1.

if [ "$(ping -c1 "$1" 2>&1)" = "ping: unknown host $1" ]

Note that ping message is probably subject to your locale settings. If you just want to test for the name resolution of a host, ping is not exactly the right tool. Try this instead:

if getent hosts "$1" > /dev/null; then ...
  • Also = instead of == as == is not standard. – Stéphane Chazelas Jul 29 '17 at 0:07
  • On my machine it works for the 'no' case but hangs for 'yes'. – Philip Kirkbride Jul 29 '17 at 0:08
  • @PhilipKirkbride ping never ends unless you use an option like -c. Answer edited. – xhienne Jul 29 '17 at 0:09
  • 1
    @PhilipKirkbride I have added an alternate syntax that does not involve ping. – xhienne Jul 29 '17 at 0:14

Not the answer you're looking for? Browse other questions tagged or ask your own question.