Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a batch file capture the exit codes of the commands it is invoking?

Tags:

Basically, let's say that I have a batch file that calls myapp1.exe and myapp1.exe exits with Exit Code 1. Can the batch file capture this information and either force the batch file to exit with that same exit code or perform some other logic?

like image 258
Matt Avatar asked Sep 09 '10 22:09

Matt


People also ask

How a batch file can be invoked?

Answer. You can programmatically invoke a batch file or executable by using the generic Java getRuntime(). exec API. All source code and/or binaries attached to this document are referred to here as "the Program".

What is Exit command on 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.

Can batch file return a value?

By default when a command line execution is completed it should either return zero when execution succeeds or non-zero when execution fails. When a batch script returns a non-zero value after the execution fails, the non-zero value will indicate what is the error number.

Can a batch file call itself?

You can create a batch program that calls itself. However, you must provide an exit condition. Otherwise, the parent and child batch programs can loop endlessly. If command extensions are enabled, call accepts <label> as the target of the call.


2 Answers

@echo off rem ... set errorlevel= MyApp1.exe exit /b %errorlevel% 

would be the explicit variant.

like image 129
Joey Avatar answered Sep 20 '22 14:09

Joey


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/

like image 32
Nate Cook Avatar answered Sep 20 '22 14:09

Nate Cook