Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: How to catch git command failure?

Tags:

git

bash

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)

like image 307
bigpotato Avatar asked Mar 10 '23 21:03

bigpotato


1 Answers

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

like image 68
Jean-François Fabre Avatar answered Mar 16 '23 05:03

Jean-François Fabre