This is yet another article about Batch files. In this article, I am going to show you how to do number counting loops in Batch files.
For more advanced Batch scripting topics, please grab a copy of the Batchography book.
In Batch files, to achieve number counting, you have to use /L switch with the FOR keyword to start a counting loop.
The following are to two syntaxes that you can use from the command line or from inside the script respectively:
FOR /L %variable IN (start, step, end) DO command [command-parameters]
And from inside a script just prefix the count variable with an extra “%”:
FOR /L %%variable IN (start, step, end) DO command [command-parameters]
Please note the most important arguments to pass to the FOR /L:
- variable: The variable name should be a single character (case sensitive) and should be prefixed with a single “%” or two of them “%%” depending on where the FOR /L is invoked from.
- start: the starting count number.
- step: the number of steps taken after each iteration. The steps can be a negative or a positive number.
- end: at which number should the counting stop (the ending number is included in the counting).
- command: The command to execute which could be a single line command or a composite command. Please refer to the Batchography book for information on composite commands.
Let’s take a simple (based on the for-count.bat script) example:
FOR /L %%i IN (10, 1, 20) DO ( ECHO i=%%I )
This simple script starts counting from 10 until 20 while incrementing the counter just once per iteration. Let’s run it and observe its output:
C:\Batchography>simple-count.bat i=10 i=11 i=12 i=13 i=14 i=15 i=16 i=17 i=18 i=19 i=20 C:\Batchography>
It is also possible to count backwards by changing the parameters by starting from a higher number, down to a lower number and specifying a negative step argument like this:
@echo off FOR /L %%i IN (20, -1, 10) DO ( ECHO i=%%i )
…and the output is:
C:\Batchography>simple-count-backwards.bat i=20 i=19 i=18 i=17 i=16 i=15 i=14 i=13 i=12 i=11 i=10 C:\Batchography>
That’s it! Simple and straight to the point. You might also like:
- Batchography: Converting numbers to characters (or the CHR() function)
- How to show saved Windows 8 and Windows 10 Wifi passwords
- How to show saved Windows 7 Wifi passwords
- Free WifiShare Tool: Turning your laptop into a hotspot and internet connection sharing station
- Free software
- How to get unlimited free Internet at Airports
- Batchography: The Art of Batch Files Programming – book
- Backup and restore NTFS files permission with the ResetPermission utility