The syntax of for loop in Windows bat file is a little strange. If you are familiar with for loop in other programming languages, you may write the following code:
for %var in (a b) do echo aa
Unfortunately, you’ll get this error:
%var was unexpected at this time.
For the Windows cmd command For, the “loop variable”, i.e. a parameter of the For command, can have only one letter. So the correct code would be:
for %g in (a b) do echo %g
Now the command(echo) after the do will be execute 2 times. Each time, %d will be substituted with one element from the in list. you can put multiple commands after do like:
for %g in (a b) do echo %g & echo hello
or using parenthesis:
for %g in (a b) do (echo %g echo hello )
You may be curious about the internals of the for loop. How is the for loop implemented? Well, when cmd reads the for loop (on one line or multiple lines), it will do the variable expansion first. So in
set b=c for %a in (a b) do ( set b=%a echo %b% )
, the for loop will expand to
for %a in (a b) do ( set b=%a echo c )
Then, the expanded for loop is mapped to a series of commands:
( set b=a echo c ) ( set b=b echo c )
These commands are executed by cmd, and you will see two cs on the screen.
The For command has quite a few switches. For example, you can use for /L to generate a list of numbers for the loop variable. You can use For /R to iterate files in the root directory(specified by the path parameter) and its sub-directories and grand-directories,etc. You can use For /D to iterate over the sub-directories. You can use For /F to extract fields from files. You can refer to this post about how to use these switches in detail.
Note that you should use %%(double percentage sign) to represent the loop variable in batch files because in batch scripts, single percentage symbol has other meaning. You can refer to this post about why double %% symbols are necessary.
Note also that the variable expansion has subtle difference for command line and bat script. If an environment variable var does not exist, %var% will be expanded to %var% in command line but empty in script. The variable expansion is done only once at parse time(compile time), not at execution time. So if you echo %var% in the for loop, you will see %var% in command line but nothing in script.