Scripting: Batch Script May Execute “Random” Sections
In Windows' Command Processor batch scripting, there is a structure called a label which enables script flow control. The syntax is:
if %Variable% EQU X (goto Label1) else (goto Label2)
echo Here is the label
echo Here is the second label
This basic semantic also allows the creation of standalone subroutines within a script:
echo Remainder of script
echo This is the label.
In this example, the script goes to the section called Label and then returns to the original code (goto :EOF).
Using a label to redirect script flow is not the same as using a label to create a subroutine. For one thing, the subroutine needs an instruction to go back to whence it was called.
Care must be taken to not mix up the two usages.
For example, it is simple to repeat a loop by directing script flow back to a label:
if CheckSomething goto Label
In this example, the section under the label will carry out some instructions, then go back to the label, and the rest of the script flow will continue if the loop condition fails.
This is not the same as using a subroutine syntax. For example, the following does work, to an extent:
if CheckSomething call :Label
However this activates a recursive loop, and each loop doesn't have a natural end because there's no goto :EOF. When the loop ends, the script will continue to run until the end of the file, but then the Command Processor will go back to the end of this section and run the commands from that point. This makes it appear that a random section is being executed for no reason.