Skip to main content

Batch Script While

While Loop

There is no direct while statement in Batch Script, but we can implement this loop very easily using the if statement and labels.

Syntax

The syntax of the general implementation of the while statement is given below:

set counters
:label
if (expression) (
do_something...
increment counter
go back to :label
)

Explanation:

  • The entire while implementation code is placed inside a label.
  • The counter variables must be set or initialized before starting the while loop implementation.
  • The expression for the while condition is executed with the if statement. If the expression is true, the corresponding code within the if loop is executed.
  • A counter must be incremented correctly within the if statement so that the while implementation can terminate at some point in time.
  • Finally, we will go back to our label so that we can evaluate the if statement again.

Example

Example of a while loop in which the variable index is initialized to 1 and incremented with each execution of the while loop until index is less than or equal to the count variable (initialized to 5):

@echo off
set /A "index = 1"
set /A "count = 5"
:while
if %index% leq %count% (
echo The value of index is %index%
set /A "index = index + 1"
goto :while
)
The value of index is 1
The value of index is 2
The value of index is 3
The value of index is 4
The value of index is 5

Table of Contents