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
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
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"
}
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 ]]
$ 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