【问题标题】:Bash script continuing, even though I want it to exit earlier [duplicate]Bash脚本继续,即使我希望它早点退出[重复]
【发布时间】:2016-12-15 23:39:49
【问题描述】:

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

#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

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

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

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

【问题讨论】:

标签: git bash sh


【解决方案1】:
git branch -D master || (echo "no master branch" && exit 1);

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

git branch -D master || { echo "no master branch" && exit 1; }

【讨论】:

  • 感谢子进程的解释!
  • 同意,但要明确一点,这不是 Done 不打印的原因
【解决方案2】:

当然,您在触发的 if 条件内调用 exit。

Exit 将以任何语言结束当前进程,包括 bash(尽管如果您正在线程化或分叉,它会变得比这更复杂,但看起来您不会同时执行任何东西)。

【讨论】:

  • Dan 看看在对 OP 的第一条评论中的链接中接受的答案以及@blitzen9872 的答案
  • 它们的相似之处只是它们都是 bash 编程错误,@AlexanderMills。
猜你喜欢
  • 1970-01-01
  • 2019-06-29
  • 1970-01-01
  • 1970-01-01
  • 2012-12-03
  • 2018-02-12
  • 2021-12-29
  • 1970-01-01
  • 2020-12-19
相关资源
最近更新 更多