for |
Use this command to repeat a specified command any number of times. You specify an arbitrary variable name and a set of values to be iterated through. For each value in the set, the command is repeated. The options used by for are the following:
for [/d] % variable in ( set ) do command [ arguments ] for /r [ path ] % variable in ( set ) do command [ arguments ] for /l % variable in (start,step,end) do command [ arguments ]
Option | Description |
---|---|
command [ arguments ] | The command to execute or the program filename to run. |
% variable | A one-letter variable name that is assigned, one-by-one, to the elements listed in set. When used in a batch file, the variable name must be preceded by two percent signs. |
set | The sequence of elements through which the for command cycles. Elements are separated with spaces, and can be files, strings, or numbers . Use the /l option for the more traditional start,step,end format. |
/d | Instructs for to match against directory names instead of filenames if set contains wildcards. Can't be used with the /l or /r options. |
/l | Specifies that set takes the form of start,step,end, allowing you to specify a range of numbers and an increment instead of having to list each element. |
/r [ path ] | Recursively executes command for each directory and subdirectory in path. If path is omitted, the current directory is used. Without /r , files specified in set only relate to the current directory. If set is just a single period ( . ), for will simply list all the directories in the tree. |
Loop three times, assigning words to the variable %n :
for %n in (rock paper scissors) do echo %n
Both of the following loops are equivalent. They repeat five times, assigning numbers 1, 2, 3, 4, and 5 to the variable %n :
for %n in (1 2 3 4 5) do md ch%n for /l %n in (1,1,5) do md ch%n
More examples:
for /l %n in (100,-2,0) do echo %n for %j in (a.txt b.txt c.txt) do copy %j a: for %x in (*.txt) do type %x for /r c:\ %i in (.) do echo %i