TExcelTAD
Home › Windows CMD & Batch › Batch for Loops

Batch for Loops

for is CMD's only loop command, but its switches turn it into several different loops: over a list of words or files, over a range of numbers, over folders, through a whole directory tree, or over the lines of text (for /f, the next lesson).

Form Loops over
for %%x in (a b c) do ... words, or files matching wildcards
for /l %%i in (start,step,end) do ... a range of numbers
for /d %%d in (*) do ... folders matching a wildcard
for /r [folder] %%f in (*.txt) do ... files in a folder and all its subfolders
for /f ... %%l in (...) do ... lines and fields of text: see for /f

The loop variable: %%x vs %x

The loop variable is a single letter, and it's case-sensitive (%%a and %%A are different). In a batch file it's written with two percent signs, %%x; typed at the interactive prompt it's %x. This lesson's examples are batch files, so they all use %%.

cmd · try it yourself
@echo off
for %%c in (red green blue) do echo colour: %%c
colour: red
colour: green
colour: blue

The list in parentheses is split on spaces, commas, semicolons and =. Put an item in quotes to keep spaces in it; %%~c removes the quotes again:

cmd · try it yourself
@echo off
for %%p in ("New York" Paris "Rio de Janeiro") do echo city: %%~p
city: New York
city: Paris
city: Rio de Janeiro

Looping over files

If a list item contains a wildcard (* or ?), for replaces it with the matching file names (folders are not included):

cmd · try it yourself
@echo off
mkdir docs
cd docs
> a-intro.txt echo one
> b-setup.txt echo two two
> c-usage.md echo three
for %%f in (*.txt) do echo found %%f
for %%f in (*.txt *.md) do echo %%f has extension %%~xf
found a-intro.txt
found b-setup.txt
a-intro.txt has extension .txt
b-setup.txt has extension .txt
c-usage.md has extension .md

Inside the loop, %%~ modifiers take the file name apart, the same modifiers you'll meet in Arguments:

Modifier Meaning Example for C:\tad\docs\b-setup.txt
%%~nf name without extension b-setup
%%~xf extension .txt
%%~nxf name and extension b-setup.txt
%%~ff full path C:\tad\docs\b-setup.txt
%%~dpf drive and folder C:\tad\docs\
%%~zf size in bytes 11
cmd · try it yourself
@echo off
mkdir reports
cd reports
> jan.csv echo 100
> feb.csv echo 250
for %%f in (feb.csv jan.csv) do echo %%~nf: %%~zf bytes, in folder %%~dpf
feb: 5 bytes, in folder C:\Users\learner\reports\
jan: 5 bytes, in folder C:\Users\learner\reports\

echo 100 writes 100 plus a line break (CR LF), so the files are 5 bytes. The listed order is the order you wrote; for wildcards, NTFS returns names alphabetically.

Counting with for /l

for /l %%i in (start,step,end) counts from start to end (inclusive) by step. The step can be negative:

cmd · try it yourself
@echo off
for /l %%i in (1,1,5) do echo line %%i
for /l %%i in (10,-3,1) do echo countdown %%i
line 1
line 2
line 3
line 4
line 5
countdown 10
countdown 7
countdown 4
countdown 1

To do arithmetic with the counter, use set /a inside the loop. And the moment you want to read a variable you changed inside the loop, you'll need delayed expansion:

cmd · try it yourself
@echo off
setlocal enabledelayedexpansion
set /a sum=0
for /l %%i in (1,1,10) do (
  set /a sum+=%%i
  echo after %%i: !sum!
)
echo total: %sum%
after 1: 1
after 2: 3
after 3: 6
after 4: 10
after 5: 15
after 6: 21
after 7: 28
after 8: 36
after 9: 45
after 10: 55
total: 55

Without enabledelayedexpansion and !sum!, every line would print the value sum had before the loop (0). That's the most important rule of loops in CMD, explained fully in setlocal & Delayed Expansion. set /a sum+=%%i is fine because set /a reads sum itself at run time.

Folders with for /d

for /d matches directories instead of files:

cmd · try it yourself
@echo off
mkdir projects\alpha projects\beta projects\gamma
> projects\readme.txt echo top
cd projects
for /d %%d in (*) do echo folder: %%d
folder: alpha
folder: beta
folder: gamma

readme.txt isn't listed: for /d skips files.

A whole tree with for /r

for /r folder %%f in (pattern) do visits the folder and every subfolder, giving you the full path of each match. Without a folder name it starts in the current directory:

cmd · try it yourself
@echo off
mkdir site\css site\img\icons
> site\index.html echo x
> site\css\main.css echo x
> site\css\print.css echo x
> site\img\icons\logo.svg echo x
for /r site %%f in (*.css *.svg) do echo %%~nxf  in  %%~dpf
main.css  in  C:\Users\learner\site\css\
print.css  in  C:\Users\learner\site\css\
logo.svg  in  C:\Users\learner\site\img\icons\

The deep paths in the output show where the script runs: from C:\Users\learner. for /r with (.) as the set lists every folder in the tree instead of files.

Several commands per iteration

Use parentheses after do. The opening ( must be on the same line as do:

cmd · try it yourself
@echo off
for %%n in (3 5) do (
  echo multiples of %%n:
  for /l %%m in (1,1,3) do (
    set /a product=%%n*%%m
    call echo   %%n x %%m = %%product%%
  )
)
multiples of 3:
  3 x 1 = 3
  3 x 2 = 6
  3 x 3 = 9
multiples of 5:
  5 x 1 = 5
  5 x 2 = 10
  5 x 3 = 15

call echo %%product%% is the old trick to read a variable that changed inside the loop without delayed expansion: call expands the line a second time.

Breaking out of a loop

There's no break. A goto to a label after the loop ends it; with for /l CMD quietly finishes counting in the background, which is slow for big ranges but harmless for small ones:

cmd · try it yourself
@echo off
for %%w in (alpha beta STOP gamma) do (
  if "%%w"=="STOP" goto after_loop
  echo word: %%w
)
:after_loop
echo loop finished
word: alpha
word: beta
loop finished

For a "skip this item" (continue), wrap the body in an if not.

Comparison with other shells

Task CMD Bash PowerShell
over words for %%w in (a b) do for w in a b; do foreach ($w in 'a','b')
numbers for /l %%i in (1,1,5) for i in {1..5} foreach ($i in 1..5)
files for %%f in (*.txt) for f in *.txt Get-ChildItem *.txt
recursive for /r %%f in (*.txt) find . -name '*.txt' Get-ChildItem -Recurse

Learn more: Bash Loops, PowerShell Loops, for /f: Parse Text.

Test yourself

How is a for loop variable written inside a .bat file?

  1. %x
  2. %%x
  3. $x
  4. !x

What does for /l %%i in (2,2,8) do echo %%i print?

  1. 2 4 6 8
  2. 2 3 4 5 6 7 8
  3. 2 4 6
  4. 8 6 4 2

Which modifier gives just the extension of %%f?

  1. %%~nf
  2. %%~xf
  3. %%~df
  4. %%~ef