5

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

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

What am I doing wrong here?

1 Answers1

5

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 ...
xhienne
  • 17,793
  • 2
  • 53
  • 69