How do you loop in a Windows batch file?
Asked Answered
I

9

194

What is the syntax for a FOR loop in a Windows batch file?

Ias answered 31/8, 2009 at 4:32 Comment(1)
ss64.com/nt/for.htmlFreezedry
L
140
FOR %%A IN (list) DO command parameters

list is a list of any elements, separated by either spaces, commas or semicolons.

command can be any internal or external command, batch file or even - in OS/2 and NT - a list of commands

parameters contains the command line parameters for command. In this example, command will be executed once for every element in list, using parameters if specified.

A special type of parameter (or even command) is %%A, which will be substituted by each element from list consecutively.

From FOR loops

Lumberjack answered 31/8, 2009 at 4:35 Comment(4)
Can I give the range (1 TO 100) in list?Ias
FOR /L %x IN (1,1,100) DO ...Maloney
put parens around [ parameters ] if you would like to include multiple lines in your for loopSulphurate
@aaiezza, I second your opinion. I'm fighting with these bloody loops right now, working completely unexpectedly, and I've no idea what is controlling anything looking at the output. Horrid stuff. Useful, but horrid.Socha
J
257

If you want to do something x times, you can do this:

Example (x = 200):

FOR /L %%A IN (1,1,200) DO (
  ECHO %%A
)

1,1,200 means:

  • Start = 1
  • Increment per step = 1
  • End = 200
Joselynjoseph answered 22/8, 2010 at 12:10 Comment(3)
Thanks for adding. Might be more clear if you change the starting value in your example to something different than the increment.Mahala
The end value is inclusive.Latashalatashia
FYI this syntax does not work in MS-DOS.Parsonage
L
140
FOR %%A IN (list) DO command parameters

list is a list of any elements, separated by either spaces, commas or semicolons.

command can be any internal or external command, batch file or even - in OS/2 and NT - a list of commands

parameters contains the command line parameters for command. In this example, command will be executed once for every element in list, using parameters if specified.

A special type of parameter (or even command) is %%A, which will be substituted by each element from list consecutively.

From FOR loops

Lumberjack answered 31/8, 2009 at 4:35 Comment(4)
Can I give the range (1 TO 100) in list?Ias
FOR /L %x IN (1,1,100) DO ...Maloney
put parens around [ parameters ] if you would like to include multiple lines in your for loopSulphurate
@aaiezza, I second your opinion. I'm fighting with these bloody loops right now, working completely unexpectedly, and I've no idea what is controlling anything looking at the output. Horrid stuff. Useful, but horrid.Socha
A
56

Type:

for /?

and you will get several pages of help text.

Allantois answered 31/8, 2009 at 4:34 Comment(2)
I prefer this over the accepted answer because it handles the different versions of DOS/Windows. "For" has been enhanced quite significantly, over the years, and the question doesn't say what version(s) is (are) being targeted nor what scenario is being attempted.Blastogenesis
This is worth a comment, but is not worth an answer.Wendelin
P
46

Conditionally perform a command several times.

  • syntax-FOR-Files

    FOR %%parameter IN (set) DO command 
    
  • syntax-FOR-Files-Rooted at Path

    FOR /R [[drive:]path] %%parameter IN (set) DO command 
    
  • syntax-FOR-Folders

    FOR /D %%parameter IN (folder_set) DO command 
    
  • syntax-FOR-List of numbers

    FOR /L %%parameter IN (start,step,end) DO command 
    
  • syntax-FOR-File contents

    FOR /F ["options"] %%parameter IN (filenameset) DO command 
    

    or

    FOR /F ["options"] %%parameter IN ("Text string to process") DO command
    
  • syntax-FOR-Command Results

    FOR /F ["options"] %%parameter IN ('command to process') DO command
    

It

  • Take a set of data
  • Make a FOR Parameter %%G equal to some part of that data
  • Perform a command (optionally using the parameter as part of the command).
  • --> Repeat for each item of data

If you are using the FOR command at the command line rather than in a batch program, use just one percent sign: %G instead of %%G.

FOR Parameters

  • The first parameter has to be defined using a single character, for example the letter G.

  • FOR %%G IN ...

    In each iteration of a FOR loop, the IN ( ....) clause is evaluated and %%G set to a different value

    If this clause results in a single value then %%G is set equal to that value and the command is performed.

    If the clause results in a multiple values then extra parameters are implicitly defined to hold each. These are automatically assigned in alphabetical order %%H %%I %%J ...(implicit parameter definition)

    If the parameter refers to a file, then enhanced variable reference can be used to extract the filename/path/date/size.

    You can of course pick any letter of the alphabet other than %%G. but it is a good choice because it does not conflict with any of the pathname format letters (a, d, f, n, p, s, t, x) and provides the longest run of non-conflicting letters for use as implicit parameters.

Pedigree answered 7/10, 2016 at 10:2 Comment(4)
How do I use for loop to get inside a previously set variable? I tried for /F "tokens=2 delims=," %%i in ( %a% ) do ( ….. but this doesn't work. It fails saying " ( was unexpected at this time"District
Hi there. Is %a% giving the name of a regular file? It's difficult to help you with this format. Feel free to ask a new question after reading How to Ask.Pedigree
@jumping_monkey, The FOR command creates parameter variables which are identified with a letter rather than a number (e.g. %%G). The path format Parameter Expansions can also be applied these. To avoid confusion between the two sets of letters, avoid using the letters (a, d, f, n, p, s, t, x, z) as FOR parameters or just choose a FOR parameter letter that is UPPER case.Pedigree
Hi @J.Chomel, So for example in a reference like %%~fG the %%G is the FOR parameter, and the ~f is the Parameter Expansion. Got it (here)[ss64.com/nt/syntax-args.html), thanks to you. Cheers mate.Abort
J
15

FOR will give you any information you'll ever need to know about FOR loops, including examples on proper usage.

Jorin answered 8/6, 2011 at 14:36 Comment(0)
A
13

Try this code:

@echo off
color 02
set num1=0
set num2=1 
set terminator=5
:loop
set /a num1= %num1% + %num2%
if %num1%==%terminator% goto close
goto open
:close
echo %num1%
pause 
exit
:open
echo %num1%
goto loop

num1 is the number to be incremented and num2 is the value added to num1 and terminator is the value where the num1 will end. You can indicate different value for terminator in this statement (if %num1%==%terminator% goto close). This is the boolean expression goto close is the process if the boolean is true and goto open is the process if the boolean is false.

Aba answered 7/8, 2012 at 7:43 Comment(1)
This is the easiest to understand. The other answers give close to no explanation on what the commands and flags do. For a javascript only kind of guy, batch files are not intuitive at all.Retroflex
C
5
@echo off
echo.
set /p num1=Enter Prelim:
echo.
set /p num2=Enter Midterm:
echo.
set /p num3=Enter Semi:
echo.
set /p num4=Enter Finals:
echo.
set /a ans=%num1%+%num2%+%num3%+%num4%
set /a avg=%ans%/4
ECHO %avg%
if %avg%>=`95` goto true
:true
echo The two numbers you entered were the same.
echo.
pause
exit
Clump answered 8/7, 2013 at 7:56 Comment(0)
S
5

From FOR /? help doc:

FOR %variable IN (set) DO command [command-parameters]

%variable Specifies a single letter replaceable parameter.
(set) Specifies a set of one or more files. Wildcards may be used. command Specifies the command to carry out for each file.
command-parameters
Specifies parameters or switches for the specified command.

To use the FOR command in a batch program, specify %%variable instead
of %variable. Variable names are case sensitive, so %i is different
from %I.

If Command Extensions are enabled, the following additional
forms of the FOR command are supported:

FOR /D %variable IN (set) DO command [command-parameters]

If set contains wildcards, then specifies to match against directory  
names instead of file names.                                          

FOR /R [[drive:]path] %variable IN (set) DO command [command-parameters]

Walks the directory tree rooted at [drive:]path, executing the FOR    
statement in each directory of the tree.  If no directory             
specification is specified after /R then the current directory is     
assumed.  If set is just a single period (.) character then it        
will just enumerate the directory tree.                               

FOR /L %variable IN (start,step,end) DO command [command-parameters]

The set is a sequence of numbers from start to end, by step amount.   
So (1,1,5) would generate the sequence 1 2 3 4 5 and (5,-1,1) would   
generate the sequence (5 4 3 2 1)                                     
Serviceable answered 1/12, 2016 at 16:51 Comment(0)
P
0

Leaving a pure MS-DOS only example here too. It's the only working example I've found:

FOR %A in (1, 2, 3, 4, 5) DO ECHO %A

enter image description here

You can also use spaces instead of commas.

Parsonage answered 29/6, 2022 at 6:45 Comment(1)
Please note it works directly in cmd only, don't work in a batch file. For batch you should double %: FOR %%A in (1, 2, 3, 4, 5) DO ECHO %%AYours

© 2022 - 2024 — McMap. All rights reserved.