After coming across this issue twice I thought I would post it here to see if anyone knows how to get around it.
I can't seem to break out of nested loops using goto
, because it looks like when it breaks out of the inner loop, the parentheses then don't match because it never reached the inner closing one.
I have narrowed this down to a very simple example
for %%a in (1,2,3) do (
for %%b in (4,5,6) do (
echo Breaking
goto :BREAK
)
:BREAK
)
This results in the error
) was unexpected at this time.
I thought maybe adding extra brackets might solve the issue but it won't help unless I know I am going to break, if it's a conditional break, it's the same problem.
Is there any easy alternative to breaking out of the inner loop back into the outer, even when it is a conditional break using if
's and else
's?
There are two steps to break from a nested loop, the first part is labeling loop and the second part is using labeled break. You must put your label before the loop and you need a colon after the label as well. When you use that label after the break, control will jump outside of the labeled loop.
Another way of breaking out of multiple loops is to initialize a flag variable with a False value. The variable can be assigned a True value just before breaking out of the inner loop. The outer loop must contain an if block after the inner loop.
Java break and Nested Loop In the case of nested loops, the break statement terminates the innermost loop. Here, the break statement terminates the innermost while loop, and control jumps to the outer loop.
If the break statement is inside a nested loop (loop inside another loop), the break statement will terminate the innermost loop.
Break by placing inner loop in a label.
for %%a in (1, 2, 3) DO (
call :innerloop
)
:innerloop
for %%b in (4, 5, 6) DO (
if %%b==<something> (
echo break
goto :break
)
)
:break
You may also omit the rest of iterations after the break with a controlling variable tied to the FOR:
@echo off
for %%a in (1,2,3) do (
echo Top-level loop: %%a
set break=
for %%b in (4,5,6) do if not defined break (
echo Nested loop: %%a-%%b
if %%b == 4 (
echo Breaking
set break=yes
)
)
)
This method preserve the code of the nested for-body in its original place and allows to easily set breaks at more than one point inside the for-body.
Antonio
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With