FOR – Windows CMD Command

Conditionally perform a command several times.

The operation of the FOR command can be summarised as…

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

%%G 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.
G > H > I > J > K > L > M
Format letters are case sensitive, so using a capital letter is also a good way to avoid conflicts %%A rather than %%a.

Nested FOR commands

FOR commands can be nested FOR %%G… DO (for %%U… do …)
when nesting commands choose a different letter for each part. you can then refer to both parameters in the final DO command.

For an example of exiting the inner loop of two nested FOR loops, see the EXIT page.

If Command Extensions are disabled, the FOR command will only support the basic syntax with no enhanced variables:
FOR %%parameter IN (set) DO command [command-parameters]

Error levels

The FOR command does not generally set any error levels, leaving that to the command being called.
One exception is using a wildcard, if the wildcard does not match any files, then FOR will return %ERRORLEVEL% = 5

FOR does not, by itself, set or clear the Errorlevel.
FOR is an internal command.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *