kar
kar

Reputation: 3651

Unable to break out of For loop to another For loop

Using a batch script, I am tying to break out of an inner for loop and land on the outer for loop to carry on the sequence but it returns an error saying:

The syntax of the command is incorrect

It is referring to the my :breakerpoint label. Please advice. Thank you.

for /l %%A in (1, 1, %NumRuns%) do (
echo Doing run %%A of %NumRuns%

    for /l %%B in (1, 1, 3) do (
        ping 127.0.0.1 -n 2 > NUL
        tasklist /FI "IMAGENAME eq Reel.exe" 2>NUL | find /I /N "Reel.exe">NUL
        echo innerloop top
    echo Error lvl is %ERRORLEVEL%
    if NOT "%ERRORLEVEL%"=="0" (
        echo innerloop middle
        goto:breakerpoint 
    )
    echo innerloop bottom
)
taskkill /F /IM "Reel.exe"
:breakerpoint rem this is error line

)
:end
echo end of run

pause

Upvotes: 4

Views: 92

Answers (1)

jeb
jeb

Reputation: 82202

A goto breaks always the current code block and the current code block is the complete block beginning with the first parenthesis, in your case you leave all nested FOR at once.

To avoid this you need to use sub functions.

for /L %%A in (1, 1, %NumRuns%) do (
    echo Doing run %%A of %NumRuns%
    call :innerLoop
)
exit /b

:innerLoop
for /L %%B in (1, 1, 10) do (
  echo InnerLoop %%B from outerLoop %%A
  if %%B == 4 exit /b
)
exit /b

Upvotes: 3

Related Questions