how to continue the next iteration in for loop

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
sambasiva
Posts: 43
Joined: 02 Jun 2013 10:25

how to continue the next iteration in for loop

#1 Post by sambasiva » 19 May 2014 03:53

Hi All,

I am looking for a continue equivalent in batch script.
Is there a way we can continue the next iteration of the for loop breaking the current iteration based on a condition.

-------
@echo off
SETLOCAL ENABLEDELAYEDEXPANSION
for /f %%A in ('dir /b C:\') do (
set value=%%A
if "!value!" EQU "test" (
echo "The test directory"
)
echo !value!
)
---------------------

if the value is equal to test I want to break the current iteration and continue with the next iteration of the for loop.

Thanks
SS

dbenham
Expert
Posts: 2461
Joined: 12 Feb 2011 21:02
Location: United States (east coast)

Re: how to continue the next iteration in for loop

#2 Post by dbenham » 19 May 2014 04:36

No, there is no built in way to do it. You cannot GOTO a label within the loop because that will immediately terminate the entire loop.

The best you can do is emulate the behavior with an IF statement. Your example could obviously be done with addition of an ELSE clause (note that I eliminated the unneeded VALUE variable):

Code: Select all

@echo off
for /f %%A in ('dir /b C:\') do (
  if "%%A" EQU "test" (
    echo "The test directory"
  ) else (
    echo %%A
  )
)

But that will not work well if dealing with multiple independent tests to continue. A solution is to use an indicator variable.

Code: Select all

@echo off
setlocal
for /f %%A in (...) do (
  set "continue="
  if "%%A" equ "condition1" (
    echo Condition 1
    set continue=1
  )
  if "%%A" equ "condition2" (
    echo Condition 2
    set continue=1
  )
  if not defined continue (
    echo Normal processing
  )
)


Dave Benham

Post Reply