How to Use the FOR Loop to Iterate Through a List of Items
One of the fundamental needs in scripting is to perform the same action on a collection of items. You might need to ping a list of servers, create a set of standard user folders, or process several specific files. The basic FOR loop in batch scripting is the perfect tool for this, allowing you to iterate through a static list of strings and execute a command for each one.
This guide will teach you the syntax of the standard FOR loop. You will learn how to define your list, how the loop variable works, and how to use it to create simple but powerful automation for repetitive tasks.
The Challenge: Repeating an Action on Multiple Items
Without a loop, if you wanted to perform the same action on three different servers, you would have to write the command three times:
PING server1.example.com
PING server2.example.com
PING server3.example.com
This is inefficient, hard to read, and impossible to manage if the list of items is long or changes frequently. The FOR loop solves this by defining the list once and then executing a template command for each item in the list.
The Core Command: The Basic FOR Loop
This is the simplest form of the FOR command. It does not use any switches (like /L, /F, or /D). Its purpose is to iterate through a simple, space-separated list of items.
Syntax: FOR %%Variable IN (Item1 Item2 Item3) DO (command)
%%Variable: A single-letter, case-sensitive variable (e.g.,%%A,%%i,%%S) that will hold the current item from the list on each iteration.IN (Set): TheSetis the list of items to iterate through, enclosed in parentheses and separated by spaces, commas, or semicolons.DO (command): The command or block of commands to be executed. The%%Variablecan be used in this command.
The Syntax: FOR %%Variable IN (Set) DO (command)
Let's break down the components with a simple example:
FOR %%i IN (Apple Banana Cherry) DO (ECHO Fruit: %%i)
- First Iteration:
%%iis set toApple. The commandECHO Fruit: Appleis executed. - Second Iteration:
%%iis set toBanana. The commandECHO Fruit: Bananais executed. - Third Iteration:
%%iis set toCherry. The commandECHO Fruit: Cherryis executed. - The loop ends because there are no more items in the set.
Basic Examples of the FOR Loop
Iterating Through a List of Names
This script uses a FOR loop to create a directory for each user in a predefined list.
@ECHO OFF
ECHO Creating user directories...
FOR %%U IN (Alice Bob Charlie David) DO (
ECHO Creating directory for user: %%U
MKDIR "%%U" 2>NUL
)
ECHO Done.
This is far cleaner and more maintainable than writing four separate MKDIR commands.
Using Wildcards to Iterate Through Filenames
A powerful feature of the basic FOR loop is its ability to use wildcards (* and ?) to generate its list from the filenames in a directory.
This script finds every .log file in the current directory and prints its name.
@ECHO OFF
ECHO --- Found the following log files ---
FOR %%F IN (*.log) DO (
ECHO Log file: "%%F"
)
Output (if files exist)
--- Found the following log files ---
Log file: "app_2023-10-25.log"
Log file: "app_2023-10-26.log"
Log file: "security.log"
Common Pitfalls and How to Solve Them
Using a Multi-Letter Loop Variable
The loop variable (%%i) must be a single letter. Using %%item is not valid syntax and will cause the command to fail. If you need a more descriptive name, you must assign the loop variable to a standard variable inside the loop.
SETLOCAL ENABLEDELAYEDEXPANSION
FOR %%i IN (Item1 Item2) DO (
SET "CurrentItem=%%i"
ECHO The current item is: !CurrentItem!
)
Handling Items with Spaces
The default delimiters for the IN clause are spaces, commas, semicolons, and the equals sign. This means that an item containing a space will be treated as two separate items.
Example of script with error
REM This will FAIL.
FOR %%N IN (John Smith) DO ECHO Name: %%N
Output:
Name: John
Name: Smith
Solution: Quote the Items
To treat an item with spaces as a single item, enclose it in double quotes.
@ECHO OFF
FOR %%N IN ("John Smith" "Mary Jones") DO (
REM Use the ~ modifier to remove the quotes for clean output
ECHO Full Name: %%~N
)
Practical Example: Pinging a List of Servers
This is a classic use case for the FOR loop. The script iterates through a list of server hostnames and runs the PING command on each one, creating a quick and simple network status check.
@ECHO OFF
SETLOCAL
SET "ServerList=server-dc01 server-fs01 server-db01 server-web01"
ECHO --- Pinging all production servers ---
ECHO.
FOR %%S IN (%ServerList%) DO (
ECHO =======================================
ECHO Pinging server: %%S
ECHO =======================================
PING -n 2 %%S
ECHO.
)
ECHO --- Ping test complete ---
ENDLOCAL
This script is easy to update; to add a new server, you just add its name to the ServerList variable.
Conclusion
The basic FOR loop is the fundamental tool in batch scripting for iterating through a predefined list of items or a set of files matching a wildcard pattern.
Key takeaways:
- The core syntax is
FOR %%i IN (Item1 Item2 ...) DO (command). - The loop variable (
%%i) must be a single character. - It can iterate through a static list or use wildcards (
*,?) to iterate through files. - To handle items with spaces, you must enclose them in double quotes.
Mastering this simple loop structure is the first step toward writing powerful and efficient automation scripts that can handle repetitive tasks with ease.