How can one batch file get the exit code of another?
Asked Answered
M

4

12

I have two batch files, task.bat and runtask.bat. The runtask.batcalls task.batand I would like runtask.bat to get the exit code of task.bat into a variable. How could this be done?

task.bat:

@echo off
set errorlevel=1

runtask.bat

...
CMD /C task.bat
set taskexitcode=????
Medeah answered 11/1, 2013 at 11:47 Comment(0)
A
14

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
Avigation answered 11/1, 2013 at 13:19 Comment(5)
Worked like a charm, thanks. It also allows variables to be set in task.bat and read in runtask.bat. Thanks very much!Medeah
Great, no worries. I didn't actually know about the variables, nice :)Avigation
The exit command has an /B switch for setting the exit code for a batch script.Yandell
@william-bettridge-radford: /B determines whether exit terminates the script or cmd.exe also. It has nothing to do with the exit code.Sectional
EXIT /? lists EXIT /B [exitCode]; it sets an exit code and returns from the subroutine or script.Yandell
B
4

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).

Batfowl answered 17/4, 2020 at 20:52 Comment(0)
C
2

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://mcmap.net/q/591582/-call-one-batch-script-in-another-batch-script-and-perform-operation-on-the-values-returned-by-first-script
http://www.borngeek.com/2008/05/22/exiting-batch-file-contexts/

Checklist answered 29/4, 2014 at 0:31 Comment(0)
Q
0

But what if we cannot call another batch file in cmd. I have SSIS package, batch file is being called internally. So I cannot call it in cmd. So even if my batch file is failing , cmd is returning as 0 - success. 😐

Quip answered 12/8 at 12:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.