Bash 脚本仍在继续,即使我希望它早点退出

Ale*_*lls 1 git bash sh

一段时间对此感到困惑,这里是一个代表问题的精炼脚本:

#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
Run Code Online (Sandbox Code Playgroud)

当我运行上面的脚本时,我得到以下输出:

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).
Run Code Online (Sandbox Code Playgroud)

请注意,“done”不会得到回显,因此脚本会在第二次 exit 1 调用时退出。但是为什么脚本在第一次 exit 1 调用时不退出呢?对此很困惑。

bli*_*872 5

git branch -D master || (echo "no master branch" && exit 1);
Run Code Online (Sandbox Code Playgroud)

在子流程环境中运行条件的 RHS。exit 退出该子进程。如果您想退出主脚本,请不要在子进程中运行它。也就是说,写:

git branch -D master || { echo "no master branch" && exit 1; }
Run Code Online (Sandbox Code Playgroud)