-2

When I run command Start C:\temp\sub2.bat in a command prompt window, errorlevel set is 4 and this is correct because a file which is indicated in batch does not exist. But when I run through this below, errorlevel returns 0. I have no idea why the exit codes are different.

Can anyone give me an advice for the reason?

@echo off
Call :Sub1
GOTO :EOF

:Sub1
start C:\temp\sub2.bat
echo %errorLevel%
Mofi
  • 46,139
  • 17
  • 80
  • 143
Muji090
  • 21
  • 2
  • 6
  • 2
    The `start` command finished successfully, the `%errorlevel%` reflects that. – Compo Jul 05 '17 at 14:33
  • Since `start` does not wait until the batch file `sub2.bat` has finished executing, you cannot get its `ErrorLevel` in the calling batch file (you'd need to add the switch `/WAIT`); you better run `sub2.bat` using [`call`](http:ss64.com/nt/call.html), then you get what you want... – aschipfl Jul 05 '17 at 20:01

1 Answers1

1

Read the answer on How to call a batch file that is one level up from the current directory? It explains the 4 methods which exist to run a batch file from within a batch file and what are the differences.

You use command start which results in starting a new command process running parallel to the command process already executing your batch file for execution of C:\temp\sub2.bat.

The current command process immediately continues the execution of posted batch file and evaluates the exit code of command start which is 0 on successfully starting the executable or batch file.

You should use the command call to run the batch file as subroutine in your batch file and which makes it possible to evaluate the exit code set by C:\temp\sub2.bat.

@echo off
call C:\temp\sub2.bat
if errorlevel 1 echo There was an error with exit code %ERRORLEVEL%.

It would be also possible to start the other batch file in a new command process and what on its termination for example with exit 4 in current batch file.

@echo off
start /wait C:\temp\sub2.bat
if errorlevel 1 echo There was an error with exit code %ERRORLEVEL%.

In general it is not advisable to use exit without option /B as this results always in exiting the command process independent on calling hierarchy which makes it also impossible to debug a batch file by running it from within a command prompt window.

In case of C:\temp\sub2.bat really contains exit ExitCode without option /B and for some unknown reason the batch file can't be edited, it is really necessary to start C:\temp\sub2.bat in a separate command process and wait for its termination with start /wait.

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

  • call /?
  • echo /?
  • exit /?
  • if /?
  • start /?

Read also the Microsoft support article Testing for a Specific Error Level in Batch Files.

See also the Stack Overflow questions:

Mofi
  • 46,139
  • 17
  • 80
  • 143