Rob van der Woude's Scripting Pages

Batch How To ...

Mimic While Loops

With the FOR command you can create loops very much like For and For Each loops available in "true" scripting langauges.
However, a recent question I received was if there is a While (or Until) equivalent in batch files.
Well... not exactly, but the following technique comes close:

:LoopStart
REM Do something
  •
  •
REM Break from the loop if a condition is met
IF ... GOTO LoopEnd
REM Iterate through the loop once more if the condition wasn't met
GOTO LoopStart
:LoopEnd

REM You're out of the loop now
  •
  •

This code can be simplified:

:LoopStart
REM Do something
  •
  •
REM Iterate through the loop once more if a condition isn't met
IF NOT ... GOTO LoopStart
REM Leave the loop if the condition was met

REM You're out of the loop now
  •
  •

These blocks of code are actually Do...Until loops.
Do...While requires the test of the condition to be done at the beginning of the block:

:LoopStart
REM Break from the loop if a condition is met
IF ... GOTO LoopEnd

REM Do something
  •
  •
REM Reiterate through the loop once more
GOTO LoopStart
:LoopEnd

REM You're out of the loop now
  •
  •

This isn't as readable as "true" scripting languages, but changing the label names might help:

:DoWhile
REM Break from the loop if a condition is met
IF ... GOTO EndDoWhile

REM Do something
  •
  •
REM Reiterate through the loop once more
GOTO DoWhile
:EndDoWhile

REM You're out of the loop now
  •
  •

Or for Do...Until loops:

:DoUntil
REM Do something
  •
  •
REM Iterate through the loop once more if a condition isn't met
IF NOT ... GOTO DoUntil
REM Leave the loop if the condition was met
:EndDoUntil

REM You're out of the loop now
  •
  •

In this last piece of code I used the :EndDoUntil label only to mark the end of the loop.
It is completely redundant as far as the batch code is concerned, no GOTO :EndDoUntil is used anywhere.

Note: Make sure every label in a batch file is unique.
If more than a single loop is used in a batch file, suffix the labels with numbers, e.g. :DoUntil1, :EndDoUntil1, :DoUntil2 and :EndDoUntil2.

page last modified: 2022-03-03; loaded in 0.0015 seconds