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: