Windows Command Prompt For Loops
last modified July 14, 2025
The For loop in Windows Command Prompt is a powerful construct for automating repetitive tasks. It can iterate through files, directories, numbers, and text data. For loops are essential for batch scripting and command-line automation. They help reduce manual work and enable complex operations.
For loops in cmd.exe come in several variants, each serving different purposes. The basic syntax includes options for iterating through files, directories, numeric ranges, and command output. Understanding these variations allows creating efficient automation scripts. For loops can be used both directly in command prompt and in batch files.
This tutorial covers all for loop variants with practical examples. We'll explore file processing, numeric iteration, text parsing, and directory traversal. Each example demonstrates real-world applications of For loops. By the end, you'll be able to implement For loops in your own scripts.
Basic For Loop Syntax
The for command has several forms, each with specific syntax and switches. The most common form processes sets of files or text data. The basic syntax uses variable substitution with percent signs in batch files.
@echo off for %%i in (1 2 3 4 5) do ( echo Number: %%i )
This simple example demonstrates the basic For loop structure. It iterates through a list of numbers and echoes each one. The %%i is the loop variable.
for %%i in (1 2 3 4 5) do
Defines a for loop with variable %%i
that takes values from the
parenthesized list. The do
keyword precedes the command to execute.
The double percent (%%) is required in batch files so that the command processor
knows to treat it as a loop variable and not as a literal % character. This
avoids confusion with environment variables, which also use %
(like %PATH%
).
echo Number: %%i
The command executed for each iteration. The %%i
is replaced with
current item value. Multiple commands can be grouped in parentheses.
C:\Users\Jano>basic_for.bat Number: 1 Number: 2 Number: 3 Number: 4 Number: 5
The output shows the loop iterating through all items in the list. This basic pattern works with any space-separated items.
Iterating Through Files
For loops are commonly used to process files matching a pattern. This example shows how to work with files in the current directory.
@echo off echo Text files in current directory: for %%f in (*.txt) do ( echo Processing: %%f type %%f )
This script finds all .txt
files and displays their contents. The
%%f
variable holds each filename in turn. The type command shows
file contents.
for %%f in (*.txt) do
It uses wildcard pattern *.txt
to match all text files. The
%%f
variable receives each matching filename. The pattern is case-insensitive.
type %%f
It displays the contents of each text file. This demonstrates processing each matched file within the loop body. Multiple operations can be performed.
Numerical For Loop
The /l switch creates numerical for loops that iterate through number ranges. This is useful for counting and repeated operations.
@echo off echo Counting from 1 to 10: for /l %%n in (1,1,10) do ( echo %%n ) echo Counting even numbers 2 to 20: for /l %%n in (2,2,20) do ( echo %%n )
This example shows two numerical loops. The first counts 1-10, the second counts even numbers 2-20. The step value controls increment size.
for /l %%n in (1,1,10) do
Creates a loop from 1 to 10 in steps of 1. The /l indicates numerical loop. Parameters are (start, step, end). All values must be integers.
for /l %%n in (2,2,20) do
Counts from 2 to 20 in steps of 2 (even numbers). The step value can be adjusted for different sequences. Negative steps count downward.
C:\Users\Jano>numeric_loop.bat Counting from 1 to 10: 1 2 3 ... 10 Counting even numbers 2 to 20: 2 4 6 ... 20
Parsing Command Output
For /f loops parse text output from commands or files. This powerful feature enables processing command results line by line.
@echo off echo Running processes: for /f "tokens=1 delims=," %%p in ('tasklist /fo csv /nh') do ( echo Process: %%~p ) echo System drives: for /f %%d in ('wmic logicaldisk get name ^| findstr ":"') do ( echo Found drive: %%d )
This script demonstrates parsing command output. The first loop processes tasklist results, the second finds disk drives. The /f switch enables parsing.
for /f "tokens=1 delims=," %%p in ('tasklist /fo csv /nh') do
Parses CSV output from tasklist command. "tokens=1 delims=," extracts first
column. /nh suppresses headers. %%p
receives each process name.
for /f %%d in ('wmic logicaldisk get name ^| findstr ":"') do ( echo Found drive: %%d )
Finds disk drives using WMIC. The caret (^) escapes the pipe for command.
%%d
receives each drive letter. No token/delimiter needed for
simple output.
Directory Recursion
For /r recursively processes directories and their subdirectories. This is useful for operations across directory trees.
@echo off echo All .exe files in C:\Windows and subfolders: for /r "C:\Windows" %%f in (*.exe) do ( echo Found: %%~nxf echo Path: %%~dpf ) echo Empty directories in current folder tree: for /r /d %%d in (.) do ( dir /a /b "%%d" | findstr "." >nul || echo Empty: %%d )
This example shows recursive file search and empty directory detection. The /r switch enables recursion through subdirectories.
for /r "C:\Windows" %%f in (*.exe) do
Recursively searches C:\Windows
for .exe
files.
%%f
gets full path to each file. %%~nxf
extracts
name+extension, %%~dpf
gets drive+path.
for /r /d %%d in (.) do
The /d switch processes directories instead of files. The (.) represents current directory in each recursion. Combined with dir/findstr, it detects empty dirs.
Processing Lines from a Text File
For loops can also process each line of a text file. This is useful for reading
configuration files, lists, or any line-based data. The for /f
command reads each line and assigns it to a variable.
apple banana cherry date
This is a simple text file with fruit names, one per line. We will read this file using a for loop in a batch script.
@echo off for /f "delims=" %%l in (fruits.txt) do ( echo Fruit: %%l )
This script reads fruits.txt
and echoes each fruit name. The
delims=
option ensures the entire line is read, including spaces.
This technique is useful for processing lists or configuration files line by
line.
C:\Users\Jano>read_lines.bat Fruit: apple Fruit: banana Fruit: cherry Fruit: date
This example demonstrates how to use for /f
to process each line of
a text file in batch scripts.
Multiplication Table with for /l
The for /l
loop is ideal for generating sequences of numbers. Here,
we use it to print the 7-times multiplication table from 1 to 10.
@echo off for /l %%i in (1,1,10) do ( set /a result=7*%%i call echo 7 x %%i = %%result%% )
This script uses set /a
for arithmetic and call
to
expand variables inside the loop. The output is:
7 x 1 = 7 7 x 2 = 14 7 x 3 = 21 ... 7 x 10 = 70
This demonstrates how for /l
can be used for numeric calculations
and repeated operations in batch scripts.
Source
Microsoft For Command Documentation
This tutorial covered essential for loop techniques in Windows Command Prompt. These examples provide foundations for building powerful automation scripts. Practice with different parameters to master for loop capabilities.