方括号必须是单独的标记!你看,它试图看起来像很好的语法,但事实是,有一个(在大多数 shell 中内置)命令[
。所以语法应该是:
if [ "$BRANCH" = "master" ]
^ ^
+--------------------+-- There have to be spaces here!
没有第一个空格,命令就变成了[master
,这样的命令不存在——命令是[
. 如果没有第二个空格,正确的参数将master]
不会匹配(并且[
会因“缺少]
参数”错误而失败。
详细说明:
shellif
语法尽量简单。真的是
if
命令 than
命令 [else
命令]fi
其中每个命令必须以分号或行尾结束。所以你可以写像
if grep -q foo somewhere
then
whatever
fi
Now in many cases you need to do things like compare strings, compare numbers, test whether file exists, test whether one file is newer than another etc. For this there is a standard command test
(which is built-in in most shells, but external version always exists). It allows things like
test "$foo" == "bar"
test -n "$this_variable_must_be_nonempty"
test -f "$this_file_should_exist"
This is what you use in if. For sake of nicer syntax, this command has alias [
which accepts exactly the same arguments, except it requires ]
as it's last argument so the condition looks pretty. This is also built-in in most shells, but usually exists as symlink to test
too. So don't be fooled by what looks like special syntax; it is simple program invocation.