FOR

Conditionally perform a command on several files.

Syntax
      FOR %%parameter IN (set) DO command

Key
   set         : A set of one or more files, separated by any standard delimiter.
                 enclosed in parentheses (file1,file2). Wildcards can be used.

   command     : The command to carry out, including any parameters.
                 This can be a single command, or if you enclose it
                 in (brackets), several commands, one per line.

   %%parameter : A replaceable parameter:
                 e.g. in a batch file use %%G 
                      (on the command line %G)

The FOR command is mostly used to process files, but you can also process a text string:
FOR %%G IN ("Hello World") DO Echo %%G
This is not really useful being much the same as Echo Hello World

Although wildcards can be used, an alternative method of processing files is to let FOR /F process the output of the command 'DIR /b' This can be useful when you want to use DIR options like sorting.

FOR parameters (%%A – %%Z)

Read the main FOR introduction page for a full description of assigning the replaceable %%parameter.

Errorlevels

FOR does not, by itself, set or clear an Errorlevel, 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 is an internal command.

Examples

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

Echo the days of the week:

FOR %%G IN (Monday Tuesday Wednesday Thursday Friday) DO Echo %%G

Echo the days of the week putting them into a sentence:

FOR %%G IN (Monday Tuesday Wednesday Thursday Friday) DO Echo Every %%G is a working day!

Copy a single file:

FOR %%G IN (MyFile.txt) DO copy %%G d:\backups\

Copy a list of several files:

FOR %%G IN (file1.txt File2.txt) DO copy %%G d:\backups\
or
FOR %%G IN ("C:\demo files\file1.txt" "C:\demo files\File2.txt") DO copy %%G d:\backups\

"Darkness reigns at the foot of the lighthouse" ~ Japanese Proverb

Related commands

FOR - Loop commands.
FOR /R - Loop through files (recurse subfolders).
FOR /D
- Loop through several folders.
FOR /L - Loop through a range of numbers.
FOR /F - Loop through items in a text file.
FOR /F - Loop through the output of a command.
FORFILES - Batch process multiple files.
GOTO - Direct a batch program to jump to a labelled line.
IF - Conditionally perform a command.
Equivalent bash command (Linux): for - Expand words, and execute commands or read (in a loop) - Read a line from standard input.


 
Copyright © 1999-2024 SS64.com
Some rights reserved