- 1 year ago
Batch Script Iterative form
In a batch script, you can create an iterative loop using a for
loop or a while
loop. The syntax and usage of each loop are slightly different. Here's how you can create an iterative loop using both methods:
For Loop:
Thefor
loop in batch script allows you to iterate over a set of values, files, or directories. The basic syntax of thefor
loop is as follows:batchfor %%variable in (set) do (
rem Your commands here
)
Example: Print numbers from 1 to 5.
batch@echo off
for %%i in (1 2 3 4 5) do (
echo %%i
)
While Loop (Using Labels and
goto
):
Batch scripts do not have a nativewhile
loop, but you can emulate it using labels and thegoto
command.Example: Print numbers from 1 to 5 using a while loop.
batch@echo off
setlocal enabledelayedexpansion
set num=1
:while
if !num! leq 5 (
echo !num!
set /a num+=1
goto :while
)
In both examples, the batch script will print the numbers from 1 to 5. You can modify the loop condition or the values in the for
loop to perform different actions in your batch script. Remember that batch scripting has limitations, and for more complex iterations, it's better to use other scripting languages like Python or PowerShell.