2016-12-15 84 views
0

去过困惑这个一段时间,这里是一个蒸馏脚本表示问题:bash脚本继续,尽管我希望它退出较早

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

请注意,“完成”没有得到回应,所以脚本退出第二次出口1呼叫。但为什么脚本不在第一次出口1呼叫时退出?对此感到困惑。

+1

看起来像这样可能会回答这个问题 - http://stackoverflow.com/questions/3822621/how-to-exit-if-a-command-failed –

回答

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

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

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

感谢您对子进程的解释! –

+0

同意,但只是要清楚,这不是为什么Done不打印 –

0

那么确定,你在if条件触发时调用exit。

退出程序将以任何语言(包括bash)结束当前进程(尽管如果您是线程或分支,它会变得比这更复杂,但它看起来不像是在同时执行任何操作)。

+0

丹在OP的第一个评论的链接中看看接受的答案,也@ blitzen9872的答案 –

+0

它只是非常相似,既是bash编程错误,@AlexanderMills。 –