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 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.
Recommended Articles for you:
- How to create variables in the batch script.
- Batch script to copy files from one folder to another folder.
- Some important Batch commands.
- How to use if-else statements in the batch script.
- Batch file introduction.