Cadzow Knowledgebase

Normal view

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:

    set Variable=Y

    if %Variable% EQU X (goto Label1) else (goto Label2)

    :Label1
    echo Here is the label
    goto Continue

    :Label2
    echo Here is the second label
    goto Continue

    :Continue

This basic semantic also allows the creation of standalone subroutines within a script:

    call :Label
    echo Remainder of script
    goto End

    :Label
    echo This is the label.
    goto :EOF

    :End

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:

    :Label
    Do Something
    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:

    :Label
    Do Something
    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.
Copyright © 1996-2019 Cadzow TECH Pty. Ltd. All rights reserved.
Information and prices contained in this website may change without notice. Terms of use.

Question/comment about this page? Please email webguru@cadzow.com.au