0


I write a function like this to .commands file, and I imported .commands in .zshrc

function testA() {
  echo "start"
  if [ "$1" == "a" ]; then
    echo "ok"
  fi
  echo "end"
}

And when I run testA a in terminal

start
testA:2: = not found

What is the problem here?

Result

Danny
  • 883
  • 8
  • 33
  • Are you sure this is the complete code? I am getting `start ok end` just fine. How are you sourcing the function code into your Bash session? – iBug Jun 30 '22 at 09:32
  • 1
    Use `if [[ "a" == "a" ]]; then` – 0stone0 Jun 30 '22 at 09:34
  • Are you sure you are using bash? what does `echo $0` say? – ciis0 Jun 30 '22 at 09:37
  • This doesn't look like Bash. Bash does not have a builtin `which` that can display shell functions. Only Zsh has a builtin `which` command that matches your output. (Also I've never seen anyone decorating Bash like that). – iBug Jun 30 '22 at 09:37
  • `echo $0` says `-zsh` – Danny Jun 30 '22 at 09:38
  • 3
    So why are you putting Bash in your question title, and tagging [tag:bash]? In case you weren't aware, Bash and Zsh are two vastly different (though partially compatible) shell implementations. – iBug Jun 30 '22 at 09:39
  • https://stackoverflow.com/questions/669452/are-double-square-brackets-preferable-over-single-square-brackets-in-b – 0stone0 Jun 30 '22 at 09:41
  • @iBug sorry for my lack of knowledge. I though they were the same. – Danny Jun 30 '22 at 09:45
  • A single "=" in the test is enough, why use two? Try "help test" in bash. – linuxfan says Reinstate Monica Jun 30 '22 at 09:49

3 Answers3

1

Chapter 12 – "Conditional Expressions" of the zsh documentation states:

A conditional expression is used with the [[ compound command to test attributes of files and to compare strings.

This means, changing your conditional expression to use [[ ... ]] instead of [ ... ] should make it work:

function testA() {
  echo "start"
  if [[ "$1" == "a" ]]; then
    echo "ok"
  fi
  echo "end"
}
lcnittl
  • 233
  • 1
  • 14
0

You can simplify the problem to simply type a [a == a] or echo ==. This will also produce this error. The reason is that a = has specific meaning to zsh, unless it is followed by a white space.

You have three possible workarounds:

Either quote that parameter, i.e.

[ $1 "==" a ]

or use a single equal sign, i.e.

[ $1 = a ]

or use [[, which introduces a slightly different parsing context:

[[ $1 == a ]]
user1934428
  • 19,864
  • 7
  • 42
  • 87
-1
    $ cat fun.sh
  function test() {
  echo "start"
  if [ "a" == "a" ]; then
    echo "ok"
  fi
  echo "end"
}

Source script file

 $ source fun.sh

Output:

$ test
start
ok
end