2

我正在为 git 存储库编写更新后脚本,但遇到了一些麻烦。

无论出于何种原因, if 语句都会引发错误:

hooks/post-update: line 5: [master: command not found

我只是想检查一下推送的分支是否等于“master”。我猜我的语法有问题,这是我的第一个 sh 脚本,但我尝试了几种变体,但都没有运气。

谢谢你的帮助,

#!/bin/sh

BRANCH=$(git rev-parse --symbolic --abbrev-ref $1)

if ["$BRANCH" = "master"]
then
    cd $HOME/domain.com || exit
else
    cd $HOME/dev.domain.com || exit
fi

unset GIT_DIR
git pull hub $BRANCH
git checkout $BRANCH
exec git-update-server-info
4

1 回答 1

3

方括号必须是单独的标记!你看,它试图看起来像很好的语法,但事实是,有一个(在大多数 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.

于 2012-08-20T12:51:16.640 回答