How to Use Batch File For Loop in Windows

A batch file is a simple text file that contains a series of commands to be executed sequentially by the Command Prompt in Windows. Batch files can be used to automate repetitive tasks, run programs, or perform file and folder operations.

One important feature of batch files is the ability to create loops, which is repeating certain commands for each element in a data set. By using loops, you can save time and effort in writing and running batch files.

In this article, we will explain how to use batch for loop files in Windows, including syntax, examples, and useful tips. We will also cover some variations of the for loop, such as for /f, for /r, and for /d, which can be used to process text files, subfolders, or directories. After reading this article, you will be able to create more efficient and flexible batch files by using for loops.

coding

What is Batch File For Loop?

A batch for loop file is a control structure that allows you to execute a specific command for each element in a data set. The data set can be a list of values, a range of numbers, or the result of another command.

The commands executed by the for loop are referred to as command blocks, and can consist of one or more lines. For each iteration of the loop, the current value of the element will be stored in a variable, which can be used in the command block.

The basic syntax of a for loop batch file is as follows:

FOR %%parameter IN (set) DO command

Where:

  • The %%parameter is a variable that stores the current value of the element. This variable must be prefixed with two percent signs (%%) if used in a batch file, or one percent sign (%) if used directly at the Command Prompt.
  • (A set is a collection of data to be processed by a loop. This set can be a list of values separated by spaces, commas, or semicolons, or a range of numbers specified with the format  (start,step,end). This set can also be the result of another command enclosed in single quotes (‘), such as  ‘dir /b’  or  ‘type file.txt’.
  • command is the command to be executed for each element in the set. This command can be an internal or external command, batch file, or command list. The variable %%parameter% can be used in this command to refer to the current value of the element. If the command consists of more than one line, it must be surrounded by parentheses (( and )).

Example:

FOR %%A IN (1 2 3) DO ECHO %%A

The above command will display the numbers 1, 2, and 3 sequentially on the screen.

FOR %%B IN (1,2,10) DO ECHO %%B

The above command will display the numbers 1, 3, 5, 7, and 9 sequentially on the screen. This is because the number range  (1,2,10)  means starting at 1, increasing by 2 each step, to a maximum of 10.

FOR %%C IN ('dir /b *.txt') DO TYPE %%C

The above command will display the contents of all text files present in the current directory.

Latest Articles