Bash:如何捕获git命令失败? [英] Bash: How to catch git command failure?

查看:86
本文介绍了Bash:如何捕获git命令失败?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一条命令:

...
{
    git filter-branch -f --env-filter "$ENVFILTER" >/dev/null
    echo "Git updated. Run 'git push -f BRANCH_NAME' to push your changes."
} || {
    echo "Git failed. Please make sure you run this on a clean working directory." // this doesn't ever get called
}

幸福的道路行得通,但它似乎并没有执行过||.这是一个失败的样子:

The happy path works, but it doesn't look like the || ever gets executed. This is what a failure looks like:

[~/Documents/my-repo]$ my-custom-command                                                                           
WARNING: Ref 'refs/heads/master' is unchanged
Git updated. Run 'git push -f BRANCH_NAME' to push your changes.
[

有没有一种方法可以捕获该错误?我不介意,即使它只是与被打印出的WARNING: Ref 'refs/heads/master' is unchanged字符串匹配(我想顺便将其隐藏)

Is there a way to catch that error? I wouldn't mind even if it was just matching the WARNING: Ref 'refs/heads/master' is unchanged string that gets printed out (which I would like to hide by the way)

推荐答案

无论如何都将执行git之后的echo命令,这是第一个问题. 第二个问题是该echo命令更新了错误代码:第一个错误代码被覆盖.

the echo command after your git will be executed no matter what, that's the first problem. The second problem is that this echo command updates the error code: first error code is overwritten.

我建议使用经典"方法(也许有点过时,我是ksh抚养长大的):

I would suggest a "classical" approach (maybe a bit old-fashioned, I was raised with ksh):

git filter-branch -f --env-filter "$ENVFILTER" >/dev/null
if [ $? = 0 ] ; then
    echo "Git updated. Run 'git push -f BRANCH_NAME' to push your changes."
else
    echo "Git failed. Please make sure you run this on a clean working directory."
fi

有点题外话:MS-DOS/Windows用户对此感到惊讶,因为在Windows中,echo不会更改ERRORLEVEL

slightly off-topic: MS-DOS/Windows users will be surprised by that, since in Windows, echo does not change ERRORLEVEL

这篇关于Bash:如何捕获git命令失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆