In this tutorial, you will learn about the batch file for loop. Likewise if else statements, loops are also used to alter the flow of program’s logic.
For loop syntax |
For loop example |
Looping through a range |
Looping through files |
Looping through directories |
Looping basically means going through something continuously until some condition is satisfied.
In batch files, there is the direct implementation of for loop only. There does not exist while and do while loops as in other programming languages.
FOR %%var_name IN list DO example_code
Here, the list is the values for which for loop will be executed. One thing to be noticed in batch file for loops is that, variable declaration is done with %%var_name
instead of %var_name%
.
Let’s take an example for illustrating batch file for loop.
@echo OFF
FOR %%x IN (1 2 3) DO ECHO %%x
PAUSE
Here in this program, we have 1, 2 and 3 in the list. So, for every element of the list the for loop will be executed and following output is generated.
Now that we know about the simple implementation of for loop, let’s implement for loop to next level.
In batch file programming, for loop can also be implemented through a range of values. Following is the syntax for implementing for loop through a range of values in the batch file.
FOR /L %%var_name IN (Lowerlimit, Increment, Upperlimit) Do some_code
Where,
The following example will highlight its concept in more details.
@echo OFF
FOR /L %%y IN (0, 1, 3) DO ECHO %%y
PAUSE
Now, this program will go through range 0 to 3, incrementing the value by 1 in each iteration.
Output
So far in for loop, we have used ‘%%’ followed by a single letter. But to loop through files using for loop, we have to use ‘%’ followed by a single letter like %y.
So here is the syntax or perhaps an example of for loop for looping through files in particular location.
FOR %y IN (D:\movie\*) DO @ECHO %y
This will go through all the files in movie folder of D: and display the files in output console.
For looping through directories, ‘/D/ is used. It is illustrated in the following example.
FOR /D %y IN (D:\movie\*) DO @ECHO %y
Now this will go through even the sub-directories inside movie folder if there exist any.
So, this is all about the batch file for loops. Please practice every piece of code on your local machine for effective learning.