Batch files are simple scripts that help automate tasks in Windows. One of the most powerful features in batch scripting is the ability to use loops. With loops, you can repeat a task multiple times, saving time and effort.
In this article, we’ll learn how to use loops in batch scripting and go through some common and useful examples.
💡 What is a Batch File Loop?
In batch programming, you can use the FOR
loop to repeat commands. The syntax for a numeric loop is:
FOR /L %%variable IN (start,step,end) DO (
command
)
- start: Starting number
- step: Increment
- end: Ending number
Let’s now look at some practical examples.
✅ Example 1: Print Numbers from 1 to 10
Here is a simple script to print numbers from 1 to 10 using a loop:
@echo off
echo Printing numbers from 1 to 10:
for /l %%i in (1,1,10) do (
echo %%i
)
pause
💬 What It Does:
This script uses a FOR /L
loop to count from 1 to 10 and prints each number on a new line.
✅ Example 2: Print “Hello World” 20 Times
@echo off
echo Printing "Hello World" 20 times:
for /l %%i in (1,1,20) do (
echo Hello World %%i
)
pause
💬 What It Does:
This script prints Hello World followed by the current loop number, 20 times.
✅ Example 3: Create 20 Folders
@echo off
echo Creating 20 folders named Folder1 to Folder20:
for /l %%i in (1,1,20) do (
mkdir Folder%%i
)
pause
💬 What It Does:
This script creates folders named Folder1
, Folder2
, …, up to Folder20
in the current directory.
✅ Example 4: Print Multiplication Table for Given Input
@echo off
set /p num=Enter a number to print its multiplication table:
for /l %%i in (1,1,10) do (
set /a result=%%i * %num%
call echo %%i x %num% = %%result%%
)
pause
💬 What It Does:
- Takes a number from the user.
- Prints its multiplication table from 1 to 10 using a loop.
call
is used to properly evaluate the variable inside the loop.
🧠 Conclusion
Using loops in batch files is a powerful way to automate repetitive tasks. Whether you want to print something multiple times, create folders in bulk, or generate a multiplication table, loops make the job easy and efficient.
Try out these examples to improve your batch scripting skills!