Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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=????
like image 763
James Avatar asked Jan 11 '13 11:01

James


People also ask

What is exit code in batch file?

EXIT /B at the end of the batch file will stop execution of a batch file. use EXIT /B < exitcodes > at the end of the batch file to return custom return codes. Environment variable %ERRORLEVEL% contains the latest errorlevel in the batch file, which is the latest error codes from the last command executed.

How do I find my return code using CMD?

To display the exit code for the last command you ran on the command line, use the following command: $ echo $?

What does %1 do in batch?

When used in a command line, script, or batch file, %1 is used to represent a variable or matched string. For example, in a Microsoft batch file, %1 can print what is entered after the batch file name.


2 Answers

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

like image 178
Michael Klishevich Avatar answered Oct 02 '22 01:10

Michael Klishevich


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
like image 43
Bali C Avatar answered Oct 02 '22 00:10

Bali C