break out of a for /l loop

Microsoft Windows
Post Reply
User avatar
MigrationUser
Posts: 336
Joined: 2021-Jul-12, 1:37 pm
Contact:

break out of a for /l loop

Post by MigrationUser »

07 Nov 2008 19:17
avery_larry

It looks like for /l loops are handled differently from other for loops . . .

To break out of a typical for loop I just stick it inside a call :label and then use exit /b

Code: Select all

dir /b>files.txt
call :process
echo done
goto :eof
:process
for /f %%a in (files.txt) do (
   if "%%a"=="killfile.txt" exit /b
   type "%%a"|find /i "ip address" >> output.txt
)
goto :eof
As best as I can tell, this does not work with a for /l loop. Any ideas for breaking out of a for /l loop? At least better than this:
thisfile.cmd:

Code: Select all

if 1%1==1loop call :loop %2
setlocal enabledelayedexpansion
set test1=yes
set test2=yes
set test3=no
set test4=doesn't matter
cmd /v:on /q /d /c "for /l %%a in (1,1,100) do call thisfile.cmd loop %%a"
echo Continuing on . . .
goto :eof
:loop
if "!test%1!"=="no" exit
echo %1
goto :eof
I may be thinking too hard since it doesn't exactly take a long time to increment a for counter when it doesn't do any other processing. Who cares if it counts up to 1000 without doing much else?

----------------------------

#2 Today 16:49
Simon Sheppard


When your second script does a CALL thisfile.cmd thats instantiating a new batch file context, so the EXIT is working and transferring control back to the first FOR /l loop.

See also a similar FOR /L bug discussed in this other thread from 2015:

viewtopic.php?f=2&t=334&p=350
Post Reply