Purpose:Create loops in batch files

 

Format:DO loop_control

commands

[ITERATE]

commands

[LEAVE [n]]

commands

ENDDO

 

Loop_control formats

 

DO count

DO FOREVER

DO varname = start TO end [BY step] [(command)]

DO WHILE condition [(command)]

DO UNTIL condition [(command)]

DO UNTIL DATETIME date time [(command)]

DO FOR n [SECONDS | MINUTES | HOURS] [(command)]

DO varname IN [range...] /D"directory" [/I:"text" /S[[+]n] /A:[[-|+]rhsadecijopt /O:[-]acdeginorstuz fileset [(command)]

DO varname IN [/T"delimiters"] /L stringset [(command)]

DO varname IN /C stringset [(command)]

DO varname IN /L stringset [(command)]

DO varname in /P command ... [(command)]

DO varname IN /Q stringset [(command)]

DO varname IN /Y arrayname [(command)]

DO varname IN @file [(command)]

 

count

Integer in the range [0, 9223372036854775807], or an internal variable or variable function that evaluates to such a value, specifying the number of times the loop is executed.

varname

The environment variable containing the current value of the loop index, or the current filename or string, or the current line from a file. Do not prefix the variable name with %.

start, end, step

Integers in the range [-9223372036854775807, 9223372036854775807] or internal variables or variable functions that evaluate to such values, controlling the number of times the loop is executed.

condition

A conditional expression to determine whether or not the loop should be executed

fileset

A filename or list of filenames, possibly using wildcards

stringset

An arbitrary set of strings. Wildcards are not interpreted.

file

A file each line of which contains a string the loop is to be executed for

range

A date, time, size or exclusion range. At most one of each, in any order.

commands

One or more commands to execute each time through the loop. If you use multiple commands, they must be separated by command separators or be placed on separate lines.

date

The loop termination date in ISO 8601 format

time

The loop termination time in 24-h hh:mm:ss format

/A:

Attribute select

/C

Loop through each character in expression

/D"directory"

Start directory

/I"text"

(Match description) Description range.

/L(iteral)

Members of set are strings, not filenames

/O:... (Order)

Sort order

/P

Parse the output of the command, saving the next output line in varname each time the loop is executed.

/Q

Like /L, but treats double quoted arguments (with embedded whitespace) as a single argument.

/S

Perform the loop in the current directory and all its subdirectories

 

Supports extended wildcards, ranges, and include lists for the set. Use wildcards with caution on LFN volumes; see LFN File Searches for details.

 

Usage

 

DO can be used in batch files, aliases, or at the command prompt. To use them in aliases or at the prompt, you need to define the DO on a single line, and enclose the body of the DO loop in a command group following the DO expression. (There is no ENDDO statement in a single-line DO). For example:

 

do count=1 to 10 by 1 (echo count=%count)

 

If the last argument on the line is a single (, it is interpreted as the beginning of a command group. DO will append the following lines (in a batch file) or prompt you for more input (at the command line) until it gets a closing ).

 

When you use DO on an LFN drive, you must quote any file names which contain white space or special characters. The same restriction may apply to names returned in the DO variable, if you pass them to TCC internal commands, or other commands which require quoting filenames with white space. DO does not quote returned names automatically, even if you included quotes in the original argument.

 

DO sets four internal variables:

 

%_do_dirsThe number of directories traversed (with /S) for the current DO loop. (I.e., nested DO's each have their own _do_dirs, _do_files, _do_errors, and _do_loop.)
%_do_filesThe number of directory entries (files or subdirectories) processed for the current DO loop.
%_do_errorsThe number of errors for the current DO loop.
%_do_loopThe number of times the current DO loop has been executed.

 

Types of DO Loops

 

DO can be used to create several different kinds of loops.

 

DO count, is a counted loop. The batch file lines between DO and ENDDO are repeated count times.

 

DO FOREVER creates an endless loop. You must use LEAVE or GOTO to exit such a loop.

 

DO varname = start TO end [BY step] is similar to a "for loop" in programming languages like BASIC. DO creates an environment variable, varname, and sets it equal to the value start. If varname already exists in the environment, it will be overwritten. DO then begins the loop process by comparing the value of varname with the value of end. If step is positive or not specified, and varname is less than or equal to end, DO executes the batch file lines up to the ENDDO. Next, DO adds to the value of varname either the value of step if BY step is specified, or 1, and repeats the compare and execute process until varname is greater than end. This example displays the even numbers from 2 through 20:

 

do i = 2 to 20 by 2

  echo %i

enddo

 

DO can also count down, rather than up. If step is negative, varname will be decreased by the absolute value of step with each loop, and the loop will stop when varname is less than end. For example, to display the even numbers from 2 through 20 in reverse order, replace the first line of the example above with:

 

do i = 20 to 2 by -2

 

DO WHILE condition evaluates condition each time through the loop as a conditional expression before executing the loop, and will execute it only if it is true. If condition is FALSE when the DO is first executed, the loop will never be executed.

 

DO UNTIL condition evaluates condition as a conditional expression each time after execution of the loop, and repeats the loop only if it is FALSE. Therefore, the statements within the loop will always be executed at least once.

 

DO UNTIL DATETIME date time executes the loop until the current date and time is equal to or greater than the specified date (ISO format) and time (24-hour format). The date and time can be in either YYYY-MM-DD HH:MM:SS or YYYYMMDDHHMMSS format. (The date and/or time can be a variable.)

 

DO FOR n SECONDS | MINUTES | HOURS executes the loop for the specified amount of time.

 

DO varname IN fileset executes the commands between DO and ENDDO by creating an environment variable, varname, and setting it equal to every filename in the fileset, ignoring items not matching file or directory names. This is similar to the set used in the FOR command, but it can only include file and directory names, not arbitrary text strings. If varname already exists in the environment, it will be overwritten (unlike the control variable in FOR). For example:

 

do x in *.txt

 ...

enddo

 

will execute the loop once for every .TXT file in the current directory; each time through the loop the variable x will be set to the name of the next file that matches the file specification. The order of matches is dependent on the file system, and is totally unrelated to any characteristics of the filenames matched.

 

If, between DO and ENDDO, you create a new file that could be included in the list of files, it may or may not appear in an iteration of the DO loop. Whether the new file appears depends on its physical location in the directory structure, a condition over which TCC has no control.

 

To use date, time, size, description, or file exclusion ranges for the set place them just before the filename(s), for example:

 

do x in /[d9-1-2018,9-31-2018] *.txt

 

DO varname IN /L stringset executes the commands between DO and ENDDO once for every string literal in stringset, setting varname to each in turn.

 

DO varname IN /C stringset executes the commands between DO and ENDDO once for every character in stringset (including whitespace and special characters), setting varname to each in turn.

 

DO varname IN @file executes the commands between DO and ENDDO once for every line in file, setting varname to the content of each one in turn. Beware of characters with special meaning to TCC, such as redirection and piping symbols, within the file (use SETDOS /X as needed).

 

To execute the loop once for each line of text in the clipboard, use CLIP: (or CLIP0: - CLIP9:) as the file name (e.g. DO X IN @CLIP:). CLIP: will not return any data unless the clipboard contains text. See Redirection for more information on CLIP:.

 

To execute the loop once for each line of text in one of the TMP temporary character devices, use TMP: (or TMP: - TMP:) as the file name (e.g. DO X IN @TMP:).  See TMP for more information on TMP:.

 

Special DO keywords: ITERATE and LEAVE

 

Two special keywords, ITERATE and LEAVE, may be used inside a DO / ENDDO loop. ITERATE ignores the remaining commands inside the loop and returns to the beginning of loop for another iteration, unless DO determines that the loop is finished. LEAVE exits from the current DO loop and continues with the command following its ENDDO. Both keywords may be repeated as often as desired. Both ITERATE and LEAVE are most often used in an IF or IFF command (group):

 

do while "%var" != "%val1"

 ...

 if "%var" == "%val2" leave

enddo

 

LEAVE accepts an optional numeric argument (>=1) which specifies the DO nesting level you want to leave. For example, "LEAVE 2" will exit two nested DO loops. You can optionally pass a variable as the LEAVE argument.

 

Usage Notes

 

  Numeric input may be entered in either decimal format (a sequence of 0-9 digits) or in hexadecimal format ("0x" followed by a sequence of 0-F hex digits).

 

DO loops can be nested, i.e. you can have a DO / ENDDO loop within another DO / ENDDO loop.

 

You can exit from all DO / ENDDO loops in a batch file by using GOTO to a line past the corresponding ENDDO. However, be sure to read the cautionary notes about GOTO and DO under the GOTO command before using GOTO in any other way inside any DO loop.

 

You cannot use RETURN to return from a GOSUB while inside a DO loop.

 

Note: Do not confuse the DO command with the unrelated optional do keyword of the FOR command.

 

Options:

 

/A:Select the files in a DO x IN ... by their specified attribute(s). See Attribute Switches for information on the attributes which can follow /A:.

 

You can specify /A:= to display a dialog to help you set individual attributes.

 

/CFor each loop, assign the next character (including whitespace and special characters) in the expression to the DO variable.

 

/D"directory"Set the start directory (for use with /S). /D supports Windows shell folder names; see CDD for details.

 

/I"text"Select files in a DO x IN ... by matching text in their descriptions. See Description Ranges for details.

 

/LThe parameters following DO x IN /L are strings, not filenames. Each parameter will be assigned in sequence, from left to right, to the loop control variable on consecutive passes through the loop. /L will not treat double quotes as delimiters; use /Q if you want to pass arguments with embedded white space.

 

/NDisable options:

 

dSkip hidden directories (when used with /S)
jSkip junctions (when used with /S)

 

/O:...Sort the files before processing.

 

You may use any combination of the sorting options below. If multiple options are used, the listing will be sorted with the first sort option as the primary key, the next as the secondary key, and so on:

 

nSort by filename and extension, unless e is explicitly included.
-Reverse the sort order for the next sort key
aSort names and extensions in standard ASCII order, instead of numerically when numeric substrings are included in the name or extension.
cSort by compression ratio
dSort by date and time (oldest first); also see /T:acw
eSort by extension
gGroup subdirectories first, then files
iSort by description
oSort by owner
rReverse the sort order for all options
sSort by size
tSame as d
uUnsorted
zSame as s

 

The /O:... option saves all of the matching filenames and then performs the requested operation. This avoids the potential problem of processing files more than once.

 

/PFor each loop, assign the next output line from command to the DO variable.

 

/QThe parameters following DO x IN /Q are strings, not filenames. Each parameter will be assigned in sequence, from left to right, to the loop control variable on consecutive passes through the loop. Unlike /L, /Q will treat double quoted arguments with embedded whitespace as a single argument.

 

/SPerform the DO loop in the current directory and then on all of its subdirectories. (DO also supports /R as a synonym, for compatibility with FOR.)

 

If you specify a number after the /S, DO will limit the subdirectory recursion to that number. For example, if you have a directory tree "\a\b\c\d\e", /S2 will only affect the "a", "b", and "c" directories.

 

If you specify a + followed by a number after the /S, DO will not execute command until it gets to that depth in the subdirectory tree. For example, if you have a directory tree \a\b\c\d\e, /S+2 will not execute command in \a or \a\b.

 

/T"text"Specify the delimiters to be used when parsing a string set.

 

/YRead a one-dimensional array and assign each value to the DO variable.  For example:

 

do x in /Y MyArray

   echo x = %x

enddo