Edmund Edmund - 1 month ago 13
Git Question

Bash: How to catch git command failure?

I have a command:

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


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)

Answer

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.

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

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