I have a batch file that's calling the same executable over and over with different parameters. How do I make it terminate immediately if one of the calls returns an error code of any level?
Basically, I want the equivalent of MSBuild's ContinueOnError=false
.
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.
If you want the command prompt cmd widnow to stay open after executing the last command in batch file –you should write cmd /k command at the end of your batch file. This command will prevent the command prompt window from closing and you'll get the prompt back for giving more commands in the cmd window.
batch-file Echo @Echo off @echo off prevents the prompt and contents of the batch file from being displayed, so that only the output is visible. The @ makes the output of the echo off command hidden as well.
Use /WAIT to Wait for a Command to Finish Execution When we start a program in a Batch file using the START command, we can wait until the program is finished by adding /wait to the START command. Even if there are multiple commands, /wait can be used for each process to finish and move to the next one.
Check the errorlevel
in an if
statement, and then exit /b
(exit the batch file only, not the entire cmd.exe process) for values other than 0.
same-executable-over-and-over.exe /with different "parameters"
if %errorlevel% neq 0 exit /b %errorlevel%
If you want the value of the errorlevel to propagate outside of your batch file
if %errorlevel% neq 0 exit /b %errorlevel%
but if this is inside a for
it gets a bit tricky. You'll need something more like:
setlocal enabledelayedexpansion
for %%f in (C:\Windows\*) do (
same-executable-over-and-over.exe /with different "parameters"
if !errorlevel! neq 0 exit /b !errorlevel!
)
Edit: You have to check the error after each command. There's no global "on error goto" type of construct in cmd.exe/command.com batch. I've also updated my code per CodeMonkey, although I've never encountered a negative errorlevel in any of my batch-hacking on XP or Vista.
Add || goto :label
to each line, and then define a :label
.
For example, create this .cmd file:
@echo off
echo Starting very complicated batch file...
ping -invalid-arg || goto :error
echo OH noes, this shouldn't have succeeded.
goto :EOF
:error
echo Failed with error #%errorlevel%.
exit /b %errorlevel%
See also question about exiting batch file subroutine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With