zsh条件OR失败

时间:2017-06-28 00:24:05

标签: zsh

# 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比较?

谢谢!

2 个答案:

答案 0 :(得分:2)

你有两个主要选择(当然也有一些不那么直接的选择)

  1. 使用zsh语法并使用[[ ... ]]代替[ ... ]

    if [[ "$BRANCH" = 'master' || "$BRANCH" = 'develop' ]]; then
    
  2. 使用-o代替||以保持POSIX兼容

    if [ "$BRANCH" = 'master' -o "$BRANCH" = 'develop' ]; then
    
  3. 如果代码只能与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
}