194

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

1

9 Answers 9

256

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
3
  • 17
    Thanks for adding. Might be more clear if you change the starting value in your example to something different than the increment. Dec 13, 2013 at 15:28
  • 7
    The end value is inclusive. Dec 11, 2016 at 2:41
  • FYI this syntax does not work in MS-DOS.
    – KERR
    Jun 29, 2022 at 6:28
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

4
  • 3
    Can I give the range (1 TO 100) in list?
    – Pradeep
    Aug 31, 2009 at 4:48
  • 38
    FOR /L %x IN (1,1,100) DO ...
    – Joey
    Aug 31, 2009 at 8:49
  • put parens around [ parameters ] if you would like to include multiple lines in your for loop Oct 22, 2015 at 19:57
  • 1
    @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.
    – RockDoctor
    Aug 19, 2019 at 23:57
55

Type:

for /?

and you will get several pages of help text.

2
  • 9
    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. Sep 27, 2012 at 3:35
  • This is worth a comment, but is not worth an answer. Aug 28 at 4:52
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.

4
  • 1
    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"
    – Shivani
    Jan 3, 2020 at 10:57
  • 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.
    – J. Chomel
    Jan 3, 2020 at 12:42
  • 2
    @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.
    – J. Chomel
    Mar 10, 2020 at 9:24
  • 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. Mar 10, 2020 at 9:32
15

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

0
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.

1
  • 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. Mar 7, 2019 at 19:16
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
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)                                     
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.

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 %%A
    – Putnik
    Sep 11 at 6:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.