Bash:如何捕获git命令失败?

时间:2016-10-17 19:50:15

标签: git bash

我有一个命令:

...
{
    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
}

快乐的道路有效,但看起来||看起来不会被执行。这就是失败的样子:

[~/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字符串(顺便说一句,我想隐藏)

1 个答案:

答案 0 :(得分:6)

echo命令将git执行后,echo将被执行,无论如何,这是第一个问题。 第二个问题是这个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 命令更新了错误代码:第一个错误代码被覆盖。

我会建议"经典"方法(可能有点过时,我是用ksh提出的):

echo

稍微偏离主题:MS-DOS / Windows用户会对此感到惊讶,因为在Windows中,ERRORLEVEL不会更改nestRemoting()