Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exiting out of a FOR loop in a batch file?

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?

like image 222
user541686 Avatar asked Jul 18 '11 05:07

user541686


People also ask

What is @echo off in batch script?

batch-file Echo @Echo off @echo off prevents the prompt and contents of the batch file from being displayed, so that only the output is visible. The @ makes the output of the echo off command hidden as well.

How do you end a batch function?

You can use goto :eof to terminate a subroutine (reaching end-of-file terminates the routine and returns to the statement after the call ) OR you can use exit or exit /b [n] as explained in the documentation (se exit /? from the prompt.

How do you exit a loop in cmd?

break command (C and C++) break ; In a looping statement, the break command ends the loop and moves control to the next command outside the loop. Within nested statements, the break command ends only the smallest enclosing do , for , switch , or while commands.

How do you stop a batch loop?

Ctrl+C. One of the most universal methods of aborting a batch file, command, or another program while it's running is to press and hold Ctrl + C . This keyboard shortcut sends a SIGINT signal, which cancels or terminates the currently-running program and returns you to the command line.


2 Answers

You could simply use echo on and you will see that goto :eof or even exit /b doesn't work as expected.

The code inside of the loop isn't executed anymore, but the loop is expanded for all numbers to the end.
That's why it's so slow.

The only way to exit a FOR /L loop seems to be the variant of exit like the exsample of Wimmel, but this isn't very fast nor useful to access any results from the loop.

This shows 10 expansions, but none of them will be executed

echo on for /l %%n in (1,1,10) do (   goto :eof   echo %%n ) 
like image 37
jeb Avatar answered Sep 22 '22 17:09

jeb


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.

like image 65
wimh Avatar answered Sep 21 '22 17:09

wimh