I have a batch file that I run from an msysgit bash shell script via cmd /c a.bat
and then I test the exit code to determine whether or not to continue. When the batch file fails, from wherever it fails, exit /b 1
is called and the batch file exits with code 1.
I recently noticed that if the batch file fails at one point where exit /b 1
is called that the exit code is not returned, and is instead 0. It only happens in an inner block. Here's an example:
@echo off
if foo EQU foo (
if bar EQU bar (
echo Exiting with code 99.
exit /b 99
)
echo this line is necessary to reproduce the issue
)
That should always exit 99, but:
X:\j\tmp>doesnotexist
'doesnotexist' is not recognized as an internal or external command,
operable program or batch file.
X:\j\tmp>echo %ERRORLEVEL%
9009
X:\j\tmp>cmd /c a.bat
Exiting with code 99.
X:\j\tmp>echo %ERRORLEVEL%
0
X:\j\tmp>cmd /c call a.bat
Exiting with code 99.
X:\j\tmp>echo %ERRORLEVEL%
99
If the last echo line is removed then cmd /c a.bat
does return exit code 99. And as I mentioned in the actual batch file the exit /b <Code>
does work most of the time.
I can reproduce in Windows 7 and 10. My question is why does it not return the exit code in the repro above? Is it a bug or something I did wrong? As you can see I tried CALL
on a hunch and it seems to remedy this issue, but I'm not sure why. CALL
is supposed to be for calling one batch from another without losing control.