Skip to main content

Batch Script For Loop in Lists

For Loop in Lists

The for construct offers looping capabilities for batch files.

Syntax

The following is the common syntax of the for statement for working with a list of values.

for %%variable in list do do_something

The classic for statement consists of the following parts:

  • Variable declaration: this step is performed only once for the entire loop and is used to declare the variables that will be used within the loop. In Batch Script, the declaration of variables is done with the %% at the beginning of the variable name.
  • List: this will be the list of values for which the for statement is to be executed.
  • The do_something code block is what needs to be executed for each iteration for the list of values.

Example

@echo off 
for %%f in (1 2 3 4 5) do echo %%f
  • The variable statement is made with a %% sign at the beginning of the variable name.
  • The value list is defined after the in clause.
  • The do_something code is defined after the echo command. Therefore, for each value in the list, the echo command will be executed.
1
2
3
4
5