Windows MS-DOS command-line interface provides different loop statements. These loop statements can be used in Batch operations. Batch operation is simply an interactive operation generally executed with a batch script at the specified intervals. In order to start the batch loop, Windows Scheduled Jobs can be used. Batch for loop can be used to iterate number list, string list, trough files, trough directories, etc.
Batch For Loop Syntax
The batch for loop has the following syntax.
for %%VARIABLE in LIST do CODE
- %%VARIABLE is the variable used to store value for each iteration.
- LIST is the list that contains multiple items to iterate with the batch for loop.
- CODE is the code block that is executed in every iteration after the %%VARIABLE is set.
Batch For Loop over Number List
The batch for loop can be used to loop over a number list. The number list consists of multiple numbers which are separated with spaces. The number list is provided inside brackets after the in
statement. The code block is after the do
statement and provides echo %%x
in order to print the %%x in every step to the command prompt.
FOR %%x IN (1 2 3 4 5) DO @echo %%x
1 2 3 4 5
Batch For Loop through Files
The batch for loop can be used to loop over files for the specified path. The path is provided like a list inside the brackets. Also, the path should provide the glob operator in order to provide folders. In the following example, we loop over files located in C:\Users\ismail\Desktop\*
.
FOR %%x IN (C:\Users\ismail\Desktop\*) DO @echo %%x
Batch For Loop through Directories
The batch for loop can be also used to iterate over directories. This is very similar to the loop for files but only directories should be iterated. In order to filter only directories the /D is used before the variable. In the following example, we iterate over directories located D:\Users\ismail\*
.
FOR /D %%x IN (C:\Users\ismail\*) DO @echo %%x
![](/wp-content/uploads/2021/06/image-140.png)