Exiting out of a FOR loop in a batch file?

user541686 picture user541686 · Jul 18, 2011 · Viewed 105.5k times · Source

Why does this batch file never break out of the loop?

For /L %%f In (1,1,1000000) Do @If Not Exist %%f Goto :EOF

Shouldn't the Goto :EOF break out of the loop?

Edit:

I guess I should've asked more explicitly... how can I break out of the loop?

Answer

wimh picture wimh · Jul 18, 2011

Based on Tim's second edit and this page you could do this:

@echo off
if "%1"=="loop" (
  for /l %%f in (1,1,1000000) do (
    echo %%f
    if exist %%f exit
  )
  goto :eof
)
cmd /v:on /q /d /c "%0 loop"
echo done

This page suggests a way to use a goto inside a loop, it seems it does work, but it takes some time in a large loop. So internally it finishes the loop before the goto is executed.