Loops

Tag(s):

Infinite loop using GOTO

@ECHO OFF
 
:Loop
 
ECHO Infinite loop. Ctrl+c to stop.
 
GOTO Loop

Conditional loop using GOTO

@ECHO OFF

REM LOOP 10 times.
SET Max=10
SET i=0
 
 
:Loop
REM If i is greater than 10, then get out of this loop.
IF %i% GTR %Max% GOTO GetOut
 
ECHO %i%

REM Increment i.
SET /A i=i+1
 
GOTO Loop
 
 
:GetOut
REM Clean up variables.
SET Max=&::
SET i=&::
 
ECHO continue processing...

FOR loop in a set

REM Loop through a defined set.
@ECHO OFF
FOR %%W IN (a B C d E whatever) DO (
ECHO %%W
)

REM ========================= OR =========================

REM Loop through each line returned by DIR command.
REM By default, the delimiter is a space. Therefore, it will not properly handle filenames with spaces.
REM To avoid this issue, use "delims=" to set the delimiter to nothing. Afterward, it will take the complete line.
FOR /F "delims=" %%W IN ('dir /s/b *.*') DO (
ECHO %%W
)

REM ========================= OR =========================

REM Use FOR loop to loop X times.
REM Syntax: FOR /L %variable IN (start,step,end) DO
FOR /L %%V IN (1,1,20) DO (
ECHO %%V
)

REM ========================= OR =========================
REM Example using token and delimiter
REM time command will output "The current time is: HH:MM:SS.mm".
REM "HH:MM:SS.mm" is the 5th token in the time command.
FOR /F "tokens=5 delims= " %%i IN ('echo ^| time ^| find "current" ') DO (
ECHO %%i
)

Can't increment environment variables within the FOR loop

DOS doesn't increment environment variables within the FOR loop. However, you can call a subroutine outside of the FOR loop and do your increment there, like this:

@ECHO OFF
 
SET i=1
FOR /L %%V IN (1,1,3) DO (
REM Will always be 1.
ECHO In Loop: %i%

REM Call Increment subroutine outside of the FOR loop.
CALL :Increment
)
 
ECHO "Other commands here after the loop."
 
GOTO :EOF
 
:Increment
  ECHO ___________Out of Loop: %i%
  SET /a i+=1
  GOTO :EOF

Note: SET /A does integer arithmetic only.