batch file for loop

batch file for loop

Like other programing language batch script supports the looping. In this article, I will explain the batch file for the loop and describe some examples of how we can use the batch file for loop in our program.

Batch File For Loop Syntax,

FOR %%Var_Name in list do  iteration_Code

 

Parameters for the batch script for loop

 

%%VarName => declaration of the variable for the “for loop” executed once.

Note: for the command prompt you can use %VarName.

List => list is the values for which for loop will be executed.

iteration_Code =>  Code block which is executed for each iteration.

 

You can see this article, Batch file commands.



Batch file for loop example

@echo OFF
FOR %%V IN (10 20 30 40) DO ECHO %%V
PAUSE

 

In the above program, I have created a list which contains the elements 10, 20,30 and 40. So, for every element of the list, the for loop will be executed and print the corresponding value.

batch file for loop

 

Batch script for loop for the range values (FOR /L)

In the batch file, we can also execute the statements according to the given range.

Syntax,

FOR /L %%Var_Name in (Expression1, Expression2, Expression3) do  iteration_Code

 

/L => /L signifies that for loop is used for iterating through a range of values.

Expression1: It is an initial value ( lower limit )for the loop.

Expression2: It is the value that will add in the initial value after each iteration.

Expression3: It is the last number for the loop.



Note: If three expressions are 0, then the body will execute indefinitely.

Let see an example, where I am echoing value from 0 to 5

@echo OFF
FOR /L %%X IN (0, 1, 5) DO ECHO %%X
PAUSE


 

When you will run the above batch file, you will get below output.

batch file for loops

 

Recommended Articles for you:



Leave a Reply

Your email address will not be published. Required fields are marked *