Home > Software design >  Why is this bash if/or string comparison not working?
Why is this bash if/or string comparison not working?

Time:10-14

I am having some trouble with a script I am using to remove old branches from a repo that have already been merged to master.

I have two branches I wish to exclude and have tried this operation:

for branchname in `git branch -r --merged origin/master`;
    if [[ "$branchname" != "origin/master" || "$branchname" != "origin/automation" ]]; then

*** delete branches ***

When I run this, "origin/master" makes it into the if statement.

But if I run only:

if [[ "$branchname" != "origin/master" ]]; then

***delete branches***

then "origin/master" does not make it into the if statement, which is correct.

What am I doing wrong in the if/or?

I am running this in a Jenkins shell script btw

CodePudding user response:

Bash is correct, the logic of your script is flawed.
If $branchname is origin/master then it still matches the second condition ($branchname != origin/automation) and the entire condition is true because of the OR operator (||).

You probably want to use AND (&&) in your condition:

for branchname in `git branch -r --merged origin/master`;
    if [[ "$branchname" != "origin/master" && "$branchname" != "origin/automation" ]]; then
        # the branch is neither `origin/master` nor `origin/automation`
        # do something with it
    fi
done

CodePudding user response:

Iterate reading rather than word split the returned string:

git branch -r --format '%(refname)' --merged origin/master |
  while read -r refname; do
    branchname="${refname#refs/remotes/}"
    case "$branchname" in
      origin/master ) continue ;;
      origin/automation ) continue ;;
      *)
        printf 'Branch %s is neither origin/master or origin/automation\n' \
          "$branchname"
        ;;
    esac
  done
  •  Tags:  
  • bash
  • Related