194

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

senshin
  • 10,022
  • 7
  • 46
  • 59
Pradeep
  • 3,420
  • 11
  • 35
  • 38

9 Answers9

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
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
vancoeverden
  • 2,821
  • 3
  • 17
  • 6
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

Andreas Rejbrand
  • 105,602
  • 8
  • 282
  • 384
rahul
  • 184,426
  • 49
  • 232
  • 263
55

Type:

for /?

and you will get several pages of help text.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
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.

J. Chomel
  • 8,193
  • 15
  • 41
  • 69
  • 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 03 '20 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 [ask]. – J. Chomel Jan 03 '20 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 '20 at 09: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)[https://ss64.com/nt/syntax-args.html), thanks to you. Cheers mate. – jumping_monkey Mar 10 '20 at 09:32
15

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Anthony Miller
  • 15,101
  • 28
  • 69
  • 98
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.

ronalchn
  • 12,225
  • 10
  • 51
  • 61
Marlon Ampoon
  • 139
  • 2
  • 3
  • 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. – user1934286 Mar 07 '19 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
Michel Keijzers
  • 15,025
  • 28
  • 93
  • 119
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)                                     
Kangaroo.H
  • 321
  • 2
  • 3
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.

KERR
  • 1,312
  • 18
  • 13