FOR loops
Basic syntax:
FOR %A IN (list) DO command [ parameters ]
list | is a list of any elements, separated by either spaces, comma's 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 from list consecutively. |
Full syntax
MS-DOS and PC-DOS (incl. Win95's MS-DOS 7.*) | as specified under basic syntax, plus VFAT/FAT32 long file name handling with LFNFOR in MS-DOS 7.* |
OS/2 Warp | as specified under basic syntax, though unlike in DOS, you may use redirection and conditional execution in the command string specified after DO |
Windows NT 4/2000/XP | as specified under basic syntax, plus many new options |
Notes
1. | %A vs. %%A |
%A is for use on command lines only. In all examples and syntax lines shown %A should be substituted with %%A when used in batch files. | |
2. | %a vs. %A |
The A in %A may be replaced by any character, either upper case or lower case, except numbers. Note, however, that variables ar case sensitive, so be consistent: | |
3. | Nesting FOR commands |
In DOS (COMMAND.COM), nesting FOR commands is not possible. However, by using a second command processor you may still be able to nest them: FOR %A IN (1 2 3) DO COMMAND /C FOR %B IN (A B C) DO ECHO %A%B Note that you cannot replace COMMAND /C with CALL In NT (CMD.EXE) nesting is possible. Note that to nest FOR loops, each loop requires its own variable; i.e. FOR %A IN (1 2) DO FOR %A IN (A B) DO ECHO %A will lead to undesired results: A FOR %A IN (1 2) DO FOR %B IN (A B) DO ECHO %A%B will work as planned, and display: 1A | |
4. | Commands in list |
list may not only contain a list of parameters, it may even contain a list of commands that can be executed consecitively with the same parameters. a.k.a. command may also be %A: | |
5. | list delimiters |
The "elements" in list can be delimited (separated) by spaces, tabs, commas or semicolons. delimiters or not. | |
6. | Forward slashes in list |
If list starts with a forward slash, COMMAND.COM (except MS-DOS 7) will split the string in list into its first character following the forward slash and the remainder of the string. | |
7. | Conditional manipulation of variables in command |
The following does not work: and then the FOR loop is started. | |
8. | Jump using GOTO in command |
FOR %%A IN (1 2 3) DO GOTO=%%A will display different results for different command interpreters:
|