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
forimplementation is placed inside a label. - The
countervariable must be set or initialized before theforloop implementation starts. - The
expressionfor theforloop is done using theifstatement. If theexpressionevaluates to be true then an exit is executed to come out of the loop. - A counter needs to be properly incremented inside of the
ifstatement so that theforimplementation can continue if the expression evaluation is false. - Finally, we will go back to our label so that we can evaluate our
ifstatement 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