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 parenthesis (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)

Examples

Copy a single file
FOR %%G IN (MyFile.txt) DO copy %%G d:\backups\

Copy a list of several files
FOR %%G IN (Myfile.txt SecondFile.txt) DO copy %%G d:\backups\

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

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.

Errorlevels

The FOR command does not generally set any errorlevels, 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.

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

Related:

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


 
Copyright © SS64.com 1999-2019
Some rights reserved