Exit in For loop - Windows Command Processor (CMD.EXE)

 picture · Jul 26, 2009 · Viewed 47.1k times · Source

I am trying to find way to break / exit from FOR loop, if there are any error occured. Below is content of batch file.

@echo on

set myfile=D:\sample.txt

FOR /F "tokens=1,2 delims=," %%i in (%myfile%) do call :process "%%i"

:process
set recfile=%1%

echo %recfile%
echo "Step in Test1"
echo %errorlevel%
pause;

exit /B 0
If %errorlevel% NEQ 0 goto :fail1

:fail1
echo "Step in fail1"
pause;
exit /B 9993

:EOF

Sample.txt has multiple records. If there are any error occured then I am expecting to exit the batch file rather then checking the complete sample.txt file. e.g. on statement echo %recfile%, If I place some wrong command ech %recfile% which is incorrect command then I am expecting that it should go to fail1 level and exit. It's catured the error code successfully and going to fail1 level however after this statment, it's checking the sample.txt file (next record) again. Is there any way, If I can break / exit FOR loop.

Please advice.

Thanks,

Answer

Shane Poznikoff picture Shane Poznikoff · Feb 23, 2011

Joey's answer is great. I have used it with success. I discovered that you don't have to exit the script though. You can use goto :SomeLabel, where :SomeLabel is a label outside of the loop.

FOR /F "tokens=1,2 delims=," %%i in (%myfile%) do (
  if defined exit goto :ParseError
  call :process "%%i"
)

@echo SUCCESS: %myfile%
goto :RestOfScript

:ParseError
@echo FAILURE: cannot parse %myfile%
@echo Using defaults...

:RestOfScript
...