Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

zsh conditional OR fails

Tags:

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
}

fails with

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)?

however if I change

if [ "$BRANCH" = 'master' || "$BRANCH" = 'develop' ]; then

to

if [ "$BRANCH" = 'master' ]; then

eveything works. How can I do OR comparison?

thanks!

like image 660
DmitrySemenov Avatar asked Sep 01 '25 00:09

DmitrySemenov


1 Answers

You have two primary options (of course there are also some less straight forward ones)

  1. Use zsh syntax and use [[ ... ]] instead of [ ... ].

    if [[ "$BRANCH" = 'master' || "$BRANCH" = 'develop' ]]; then
    
  2. Use -o instead of || in order to stay POSIX compliant

    if [ "$BRANCH" = 'master' -o "$BRANCH" = 'develop' ]; then
    

If the code is only ever to be run with zsh, I would recommend to go with 1.


The reason for the error message is that [ is only a regular command and not part of the zsh syntax. [ expects ] as last parameter, but || is part of the zsh syntax and has priority. It acts as a separator between commands and splits the "condition" into two commands

[ "$BRANCH = 'master'

and

"$BRANCH" = 'develop' ]

The second command is run, if the first one fails.

Running the first command fails, as the the closing ] is missing. This leads to the error message:

git--:[:8: ']' expected

For the second command "$BRANCH" is substituted by the value master. As there is no command named master this returns the error message

zsh: master: command not found...
like image 157
Adaephon Avatar answered Sep 04 '25 03:09

Adaephon