For Loop in DOS Batch

By | 2023-05-25

In batch scripting, you can use a for loop to iterate over a set of values or files. The for loop in batch files has different variations, such as for /F, for /R, and for %%variable. I’ll show you an example of a basic for loop using the for %%variable syntax.

Here’s the general structure of a for loop in a batch file:

@echo off
for %%variable in (list) do (
   rem Do something with each iteration
 rem You can access the current value using %%variable
)

Let’s say you want to loop through a list of numbers from 1 to 5. You can modify the loop as follows:

@echo off
for %%i in (1 2 3 4 5) do (
 echo %%i
 rem Do something with each number
)

In this example, the loop variable %%i takes on the values from 1 to 5 in each iteration. The echo %%i statement displays the current value of %%i, and you can replace it with your own commands or actions.

Note that if you’re running the code directly in a command prompt (not in a batch file), you need to use a single percent sign % instead of %% for the loop variable.

Feel free to adjust the loop parameters and customize the code within the loop to suit your specific needs.

Author: dwirch

Derek Wirch is a seasoned IT professional with an impressive career dating back to 1986. He brings a wealth of knowledge and hands-on experience that is invaluable to those embarking on their journey in the tech industry.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.