Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Breaking out of nested for loop in batch file

Tags:

batch-file

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?

like image 895
Bali C Avatar asked Jan 28 '13 12:01

Bali C


People also ask

How do you break a loop out of a nested loop?

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.

How do you break out of multiple loop levels?

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.

How do I break out of nested loops in Java?

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.

Does break () break out of innermost for loop?

If the break statement is inside a nested loop (loop inside another loop), the break statement will terminate the innermost loop.


2 Answers

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
like image 109
Gaurav Kolarkar_InfoCepts Avatar answered Sep 29 '22 23:09

Gaurav Kolarkar_InfoCepts


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

like image 40
Aacini Avatar answered Sep 30 '22 00:09

Aacini