Batch file for loop

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.

Batch File For Loop Syntax

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.

Batch file for loop example

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

batch file for loop

Now that we know about the simple implementation of for loop, let’s implement for loop to next level.

 [adsense1]

Batch file for loop – looping through a range of values

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,

  • /L signifies that for loop is used for iterating through a range of values
  • Lower limit is the value from which loop will start until it reaches the Upper limit and the increment is the value with which lower limit will be increased during each iteration

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

batch file for loop range

Batch file for loop – looping through files

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.

Batch file for loop – looping through directories

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.