17

I've been looking everywhere for what should be a simple example. First time trying to script something for zsh now that MacOS has switched over to it as default - how do I compare two strings in an if statement? I tried the following but continue to receive the error no matches found: [foo==foo]

if ["foo"=="foo"]
then
    echo "True"
else
    echo "False"
fi
Doofitator
  • 173
  • 1
  • 1
  • 4

1 Answers1

13

How do I compare two strings in an if statement?

Use the following:

if [[ "foo" == "foo" ]] 
DavidPostill
  • 153,128
  • 77
  • 353
  • 394
  • 4
    Maybe it's worth pointing out that the __white space__ around the operator `==` is essential, and not the doubled brackets as one might guess. – mpy Apr 20 '20 at 18:08
  • @mpy I would if I could find a good reference - I did look .... – DavidPostill Apr 20 '20 at 18:10
  • I neither have found a statement in the manual, but even with `[[` (which should always be preferred over `[`, please don't get me wrong on that) you don't get the desired behavior without white spaces around the operator. – mpy Apr 20 '20 at 20:50
  • 4
    @mpy - I get `zsh: = not found` , if I have no whitespace between `foo` and the square brackets `[]` - like this `if ["foo" == "foo"] or [["foo" == "foo"]]`, and no errors with no whitespace between **foo** and the double equality sign **==** with either `[[ "foo"=="foo" ]] or [ "foo"=="foo" ]`, so as per my experiments it's most important to have space between the square brackets and the string/variable start point and end point like this `[[ "foo"=="foo" ]]` and not like this too `if [["foo"=="foo"]] `, which produces error like `zsh: no matches found: [[foo==foo]]` – aspiring1 May 23 '21 at 12:06
  • @aspiring1: Yes, you are right! I obviously mixed something up, the white space around the brackets is important. This is sensible, because the `[` was first implemented as an external function, so it has to be separated from its arguments. And probably this was then taken onward to the shell built-ins `[` and `[[`. – mpy May 24 '21 at 10:08