A guide to using goto with labels and call with batch files in order to control execution flow within a batch file in DOS or Windows Command Prompt.
Batch file programming is a very useful way to automate small, repetitive, tasks. For those who are new to creating batch files, the Windows Command Line Programming tutorial is a good starting place to read about the basics of batch file programming.
Unlike other programming languages, batch programming only offers the GOTO command to control flow within a batch script. The CALL keyword can be used to call another batch script, and then return to the current script afterwards. Outside these 2 mechanisms there are no other flow control possibilities, but they are flexible enough to build quite complex solutions.
There are 2 possible ways to use the GOTO keyword - to transfer control to a label or to the end of (and exiting) the batch script without defining a label. A label is a named entry in the batch file that is declared by having a colon in front of it. The label may be before or after the GOTO keyword which refers to it. This makes it possible to loop within a file.
For example, to process a command until it fails, the following might be used:
The last GOTO :EOF is not strictly required, but is used here as an illustration.
The CALL keyword can also be used in one of 2 possible ways - to call a batch script (with parameters) in the usual way (starting at the top), or with a label that is known to exist in the batch file being called. The first version of the CALL command is simple:
The second version, with the label, looks like the following:
It is important to note that, unlike the regular CALL command, this second version creates a new context for the batch script to run in. Due to this, the called script must return with a call to GOTO :EOF. Otherwise, the second time it is exited naturally, the calling batch script will also exit.
In the above example, the CALL keyword is also used with parameters. Any parameters used in the calling script can be passed called scripts in the usual manner.
A final note: pipes and redirection can not be used with the CALL keyword, but batch files can call themselves recursively. As with all recursion, it is the responsibility of the programmer to make sure that they define an exit condition.