Page 1 of 1

how to continue the next iteration in for loop

Posted: 19 May 2014 03:53
by sambasiva
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

Re: how to continue the next iteration in for loop

Posted: 19 May 2014 04:36
by dbenham
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