# delete git branch
git--() {
BRANCH=$1
if [ -n $BRANCH]; then
BRANCH=$(git rev-parse --abbrev-ref HEAD)
fi
if [ "$BRANCH" = 'master' || "$BRANCH" = 'develop' ]; then
red "You should not delete $BRANCH"
return 0
fi
}
失败
git--:[:8: ']' expected
zsh: master: command not found...
git--:8: command not found: master
No branch specified therefore I'm using the current one: master
On branch master
nothing to commit, working tree clean
Do you really want to delete the branch master (y/n)?
但是,如果我改变
如果[" $ BRANCH" =' master' || " $ BRANCH" ='开发' ]。然后
到
如果[" $ BRANCH" =' master' ]。然后
eveything有效。我怎么做OR比较?
谢谢!
答案 0 :(得分:2)
你有两个主要选择(当然也有一些不那么直接的选择)
使用zsh
语法并使用[[ ... ]]
代替[ ... ]
。
if [[ "$BRANCH" = 'master' || "$BRANCH" = 'develop' ]]; then
使用-o
代替||
以保持POSIX兼容
if [ "$BRANCH" = 'master' -o "$BRANCH" = 'develop' ]; then
如果代码只能与zsh
一起运行,我建议使用1。
错误消息的原因是[
只是常规命令而不是zsh
语法的一部分。 [
期望]
作为最后一个参数,但||
是zsh
语法的一部分并具有优先权。它充当命令之间的分隔符,并将“条件”分成两个命令
[ "$BRANCH = 'master'
和
"$BRANCH" = 'develop' ]
如果第一个命令失败,则运行第二个命令。
运行第一个命令失败,因为缺少结束]
。这会导致错误消息:
git--:[:8: ']' expected
对于第二个命令,"$BRANCH"
由值master
替换。由于没有名为master
的命令,因此返回错误消息
zsh: master: command not found...
答案 1 :(得分:1)
你应该在调试模式下运行shell脚本,例如'zsh -x',它会在每一步中吐出变量,这样你就可以很好地理解正在发生的事情。
BRANCH变量在这里遭到破坏; -n检查BRANCH是否有值,如果是,则更新它。我希望你打算使用-z开关;
if [ -n $BRANCH]; then
BRANCH=$(git rev-parse --abbrev-ref HEAD)
fi
我认为你的脚本应该更像
git--() {
BRANCH=$1
if [ -z "$BRANCH" ] ; then
BRANCH=$(git rev-parse --abbrev-ref HEAD)
fi
if [ -z "$BRANCH" ] ; then
if [ "$BRANCH" = 'master' ] || [ "$BRANCH" = 'develop' ] ; then
red "You should not delete $BRANCH"
return 0
else
git branch $BRANCH -D || ( red "Could not delete $BRANCH" && return 1 )
fi
else
red "branch not understood"
return 1
fi
}