Exiting the For Loop - Windows Command Processor (CMD.EXE)

I am trying to find a way to exit the FOR loop if an error occurs. The following is the contents of the 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 several entries. If any error occurs, I expect to exit the batch file and then check the full sample.txt file. for example according to the statement echo% recfile%. If I put the incorrect command ech% recfile%, which is the wrong command, then I expect it to go to the fail1 level and exit. He successfully coded the error code and switched to the fail1 level, however after this state he again checks the sample.txt file (next record). Is there a way if I can break / exit the FOR loop.

Please advice.

Thanks,

+6
command-line cmd for-loop control-flow
source share
3 answers

The answer to Joe is very great. I have used it with success. I found that you do not need to exit the script. You can use goto :SomeLabel , where :SomeLabel is a label outside 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
 ...

+5
source share

You can set a variable meaning that the full loop should be interrupted and use it as follows:

 :fail1 echo "Step in fail1" pause set exit=1 

And you change the loop like this:

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

(broken into several lines for readability).

Since you simply call the routine from the for loop, it is not possible for this routine to exit the loop directly. Hence, a workaround with a variable.

+4
source share

You do not need to call a label

 set USBDRIVE=SETLOCAL set exit=ENABLEDELAYEDEXPANSION FOR %%D IN (CDEFGHIJKLMNOPQRSTUVW XYZ) DO ( DIR %%D:\SOURCES\INSTALL.WIM > nul 2>&1 && call set USBDRIVE=%%D: && call set exit=1 if defined exit goto :dd3 ) :dd3 
+2
source share

All Articles