For

Index

The FOR command is used to run a specified command or series of commands for each file in a set of files. FOR is usually used in batch programs but can also be used at the command prompt.

Syntax:

FOR %variable IN (set) DO command

%variableA single character that acts as a replaceable marker parameter. When used in batch files, %variable must be preceded by a second % sign (to become %%variable).
To avoid confusion with the batch file parameters %0 - %9, variable can be any character except the numerals 0 - 9.
%variable is replaced with each member of set until command has processed all them all.
setA list of text strings (eg. file names), separated by spaces, to be processed by command. Wildcards for filenames are recognized (but see notes below). set must be enclosed in parentheses.
commandThe command, complete with any required parameters and/or switches, to carry out for each file. Often one of the parameters will be variable - being the file in set to be operated on.

Notes:

  1. In complex batch programs, multiple values for variable can be used to distinguish different replaceable variables.

  2. FOR commands can contain IF clauses but not a second FOR.

  3. It is not hard to construct a complex FOR statement that is virtually impossible for normal mortals to decipher (even if it does work).

  4. By default, FOR only recognises short (8.3) filenames in set unless a long filename is explicitly stated (no wildcards). However, if a FOR operation produces a long filename, these are handled without difficulty.
    The LFNFOR command can be used to enable full long file name support.

Examples:

To display the contents of all the files in the current directory that have the extension ".doc" or ".txt":
FOR %v IN (*.doc *.txt) DO TYPE %v
Each file that has the ".doc" or ".txt" extension in the current directory is substituted for the %v variable until the contents of every such file are displayed.

To use this command in a batch file, it would be written:
FOR %%v IN (*doc *txt) DO TYPE %%v
If the double % sign is not used, the variable is not recognised and an error message is displayed.

Note, however, that
FOR %v IN (lettershome*.doc notestotheboss*.txt) DO TYPE %v
will find no matches unless there is a previous LFNFOR On command.

File Details:

Internal


If you should have any comments or suggestions,
please contact: Bob Watson
.
This page last revised:
December 9, 1999.