M
M
Miguel De Cervantes2016-02-11 19:06:54
git
Miguel De Cervantes, 2016-02-11 19:06:54

How to properly get error code from git command in batch script?

Hello. I had the most banal need, using a batch script, to update the local git repository and, in case of any error, return the log and error code. But I came across this very strange situation:
The git command returns an error (IF ERRORLEVEL 1 = TRUE, i.e. error code >= 1, i.e. != 0), but the error code - echo %errorlevel% outputs "0".
Tried a different validation method, used a logical OR (i.e. execute the second part only if the previous one returned an error, the "||" operator) and the same thing.
Therefore, several questions arise:
1) the error code itself is not so important to me, but because of this I doubt whether it is possible to use "IF ERRORLEVEL 1" as a check? Is it reliable?
2) Is there any way to still get the error code?
3) How is this even possible?!
All of these options output "ERRORCODE_IS_0":

git checkout master && git remote update -p && git merge --ff-only 
IF ERRORLEVEL 1 echo ERRORCODE_IS_%errorlevel%

git checkout master && git remote update -p && git merge --ff-only || echo ERRORCODE_IS_%errorlevel%

I generate an error simply: the impossibility of fast-forward. Here is the actual output of the command:
Already on 'master'
Your branch and 'origin/master' have diverged,
and have 14 and 19 different commits each, respectively.
(use "git pull" to merge the remote branch into yours)
Fetching origin
fatal: Not possible to fast-forward, aborting.
ERRORCODE_IS_0

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
res2001, 2016-02-11
@migs911

Get the error code:
[command]
set err=%errorlevel%
echo. Then we do whatever we want with the error code: %err%
You can process it as recommended in the if /? help:
goto answer%errorlevel%
:answer1
...
:answer2
...
if errorlevel 1 is quite safe to use, but too cumbersome and disposable. I usually prefer the || operator.
By the way, many command line utilities fail to return an error code :(

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question