Skip to main content

Batch Script For Classic Implementation

For Classic Implementation

The following syntax is the classic for instruction, available in most programming languages.

for(variable declaration;expression;Increment) {
statement #1
statement #2

}

The Batch Script language does not have a direct for statement similar to the syntax described above, but it is still possible to make an implementation of the classic for statement using if statements and labels.

set counter
:label

if (expression) exit loop
do_something
increment counter
go back to :label
  • The entire code of the for implementation is placed inside a label.
  • The counter variable must be set or initialized before the for loop implementation starts.
  • The expression for the for loop is done using the if statement. If the expression evaluates to be true then an exit is executed to come out of the loop.
  • A counter needs to be properly incremented inside of the if statement so that the for implementation can continue if the expression evaluation is false.
  • Finally, we will go back to our label so that we can evaluate our if statement again.

Example

@echo off 
set /A i=1
:loop

if %i%==5 goto END
echo The value of i is %i%
set /a i=%i%+1
goto :LOOP
:END
The value of i is 1
The value of i is 2
The value of i is 3
The value of i is 4