Loop Implementation at Windows Batch Programming


The windows command shell (cmd.exe) is not an ideal programming language because it was not made for this! However, you could still implement the loop using the following two methods.

Goto label

You can define a label using syntax :label and goto :label to jump to. The set /a command performs arithmetic operations/assignment and you can use if statement to check the loop variable. Not straightforward, but essentially, in computer, all loops will be decompose into something like this, the assembly view of point.

@ECHO OFF
SET /A counter=0
:top
SET /A counter=%counter%+1
ECHO Timer %counter%
if %counter% LSS 10 GOTO :top
ECHO Run complete @ http://HelloACM.com

305f8e1fd80ce53d5a4f0a221bc8790b Loop Implementation at Windows Batch Programming batch script beginner DOS implementation programming languages tricks windows windows command shell

For statement

The above method almost works on every shell versions, even on vintage DOS. However, on modern OS, the command shells are actually the enhanced emulator. Therefore, there is a command for which is made for this.

The for /l performs such tasks, the above can be shorten into a better syntax.

@ECHO OFF
for /l %%x in (1, 1, 10) echo Timer %%x
ECHO Run complete @ http://HelloACM.com

In batch file, you have to use %% instead of single % at command line. The three parameters in the brackets are start, step and stop integers.

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
327 words
Last Post: How to Print Pascal Triangle in C++ (with Source Code)
Next Post: Tiny Javascript Function to Redirect to Different Pages Given Different Screen Resolution

The Permanent URL is: Loop Implementation at Windows Batch Programming

Leave a Reply