Batch Script - Looping through Ranges


Advertisements

The ‘for’ statement also has the ability to move through a range of values. Following is the general form of the statement.

Syntax

FOR /L %%variable IN (lowerlimit,Increment,Upperlimit) DO do_something

Where

  • The /L switch is used to denote that the loop is used for iterating through ranges.

  • Variable declaration – This step is executed only once for the entire loop and used to declare any variables which will be used within the loop. In Batch Script, the variable declaration is done with the %% at the beginning of the variable name.

  • The IN list contains of 3 values. The lowerlimit, the increment, and the upperlimit. So, the loop would start with the lowerlimit and move to the upperlimit value, iterating each time by the Increment value.

  • The do_something code block is what needs to be executed for each iteration.

Following is an example of how the looping through ranges can be carried out.

Example

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

Output

The above program produces the following output.

0 
1 
2 
3 
4 
5
batch_script_return_code.htm
Advertisements