Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get return/exit code of a batch file started with START command?

I am trying to run a batch file with start /high and still get the return/exit code, i.e. %ERRORLEVEL%. The problem seems to be that command START does not return the exit code that the batch file returns.

We have a simple batch file for testing named BatFileThatReturnsOne.bat.

The contents of BatFileThatReturnsOne.bat are

EXIT /B 1

We are calling this as such:

start /high /wait BatFileThatReturnsOne.bat

But no matter what the batch file returns, the execution of start never has a %ERRORLEVEL% of anything other than 0 (zero).

This is all actually called by cfn-init in CloudFormation, but that is probably not relevant because we can reproduce it from a command line window.

The actual call is:

cmd.exe /C start /high /wait BatFileThatReturnsOne.bat

How do I get start to set the %ERRORLEVEL% to something other than 0 (zero)?

like image 725
Tim Bassett Avatar asked Mar 04 '17 15:03

Tim Bassett


People also ask

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 @echo off do in a batch file?

To prevent echoing a particular command in a batch file, insert an @ sign in front of the command. To prevent echoing all commands in a batch file, include the echo off command at the beginning of the file.

How do I get an exit code?

To check the exit code we can simply print the $? special variable in bash. This variable will print the exit code of the last run command.

What is %% R in batch command?

/r - iterate through the folder and all subfolders, i.e. recursively. %%I - placeholder for a path/filename. The above command simply lists all files in the current folder and all subfolders. Follow this answer to receive notifications.


2 Answers

directly from a cmd window or a batch file you can use

start /high /wait cmd /c BatFileThatReturnsOne.bat

but if you need to start the cmd instance to execute the start command that launchs the batch file then you can use

cmd /v /e /c" start /high /wait cmd /c launched.cmd & exit ^!errorlevel^!"
like image 76
MC ND Avatar answered Oct 12 '22 16:10

MC ND


Just change EXIT /B 1 by EXIT 1.

As explained in the Table 4 given in this answer about START /WAIT bat command:

When the started Batch file ends, set ERRORLEVEL = value from 'EXIT number' commmand.
like image 24
Aacini Avatar answered Oct 12 '22 15:10

Aacini