How can one batch file get the exit code of another?
I had a batch script in Teamcity pipeline and it did not exit after it's child script did exit with code 1.
To fix the problem I added this string IF %ERRORLEVEL% NEQ 0 EXIT 1
after the child script call.
main-script.bat
...some code
call child-script.bat
IF %ERRORLEVEL% NEQ 0 EXIT 1
...some code
After the child script call, exit result is save to %ERRORLEVEL%
. If it did exit with error the value would be not equal to 0. So we check this and if it is the case we exit with code 1 (error).
The accepted answer is correct, but if you are using call
to call another batch script, and that second batch script is using SetLocal
, you may need to use a parsing trick to accomplish this. If you are running into this, add the following code before your exit b
:
ENDLOCAL&set myvariable=%myvariable%
Now the value of myvariable
is made available to the calling context and you can see the value in the other script.
References:
https://stackoverflow.com/a/16167938/89590
http://www.borngeek.com/2008/05/22/exiting-batch-file-contexts/
Just swap CMD /C
for call
.
task.bat:
@echo off
set errorlevel=15
runtask.bat
call task.bat
set taskexitcode=%errorlevel%
echo %taskexitcode%
Output
15