1

Been confused about this for awhile, here is a distilled script that represents the problem:

#start    
# note that master does not exist, so this should fail, would like to exit on the next line
git branch -D master || (echo "no master branch" && exit 1);
git fetch origin &&
git checkout master &&

BRANCH=$(git rev-parse --abbrev-ref HEAD)
if [[ "$BRANCH" != "master" ]]; then
  echo 'Aborting script because you are not on the right git branch (master).';
  exit 1;
fi

echo "done"
#end

when I run the above script, I get this output:

error: branch 'master' not found.
no master branch
error: Your local changes to the following files would be overwritten by checkout:
        publish-to-NPM.sh
Please, commit your changes or stash them before you can switch branches.
Aborting
Aborting script because you are not on the right git branch (master).

Note that "done" does not get echoed, so the script does exit on the second exit 1 call. But why doesn't the script exit on the first exit 1 call? So confused about this.

Alexander Mills
  • 90,741
  • 139
  • 482
  • 817

2 Answers2

5
git branch -D master || (echo "no master branch" && exit 1);

is running the RHS of the conditional in a subprocess environment. The exit exits that subprocess. If you want to exit the main script, don't run it in a subprocess. That is, write:

git branch -D master || { echo "no master branch" && exit 1; }
blitzen9872
  • 320
  • 1
  • 7
0

Well sure, you call exit within the if condition that's firing.

Exit is going to end the current process in any language, including bash (though if you're threading or forking, it gets more complicated than that, but it doesn't look like you're concurrently executing anything).

erik258
  • 14,701
  • 2
  • 25
  • 31