DOS – Defining a LOOP in a Batch DOS file

The commands available in batch files are limited and don't include the programming constructs, such as indexed iteration, found in more sophisticated programming languages. But there some techniques that can be used to help you do what you want.

[tweet]

In the old-style DOS world which batch files came from, you can define and use environment variables which can be used to pass information between batch files. The following batch file uses two environment variables called max and count. It also uses a goto statement to create a loop.

@ECHO OFF

SET max=.oooo
SET count=.
:LOOP
ECHO hello there
SET count=%count%o
IF NOT %count%==%max% (GOTO LOOP)
SET max= SET count=
ECHO all done

At the beginning of the batch file the max and count are initalized with the latter being set to a period. At the top of the loop (marked by the label :LOOP) some text is echoed to the screen followed by a set statement that tacks an "o" to the end of the environment variable count. Next, the if statement compares the values of max and count.

If they are not equal the loop will be repeated. Otherwise, processing will continue with the next statement in the batch file. The last two set statements are used to remove the variables max and count from the environment space.

Note: When defining an environment variable, you use a single equal sign followed by the text string you wish to assign to the variable. When you want to refer to the value stored in an environment variable, you must enclose the variable name in percent signs as was done in lines 6 and 7 of the batch file. Line 6 is taking the current value of count, appending an "o" to it, and then storing the results back in the variable count.

By the way, it is possible to pass up to 9 variables from the command line to a batch file. For example, if you had a batch file called stuff.bat and you typed "stuff a b c d" at the command prompt, the letters "a", "b", "c", and "d" would be assigned to the variables %1, %2, %3, and %4, respectively.

Hope this helps.

SOURCE

LINK

LANGUAGE
ENGLISH