Search code examples
batch-filedelayedvariableexpansion

Windows Batch File - ENABLEDELAYEDEXPANSION query


Having read an existing post on stackoverflow and done some reading around on the net. I thought it was time to post my question before I lost too much hair!

I have the following code within a batch file which I double click to run, under Windows XP SP3:

SETLOCAL ENABLEDELAYEDEXPANSION

::Observe variable is not defined
SET test

::Define initial value
SET test = "Two"

::Observe initial value is set
SET test

::Verify if the contents of the variable matches our condition
If "!test!" == "Two" GOTO TWO

::First Place holder
:ONE

::Echo first response
ECHO "One"

::Second Place holder
:TWO

::Echo second response
ECHO "Two"

::Await user input
PAUSE

ENDLOCAL

Basically I am trying to establish if I can navigate through my script using conditionals. It seems apparent that I am getting some issues with variable scope and delayed variable expansion yet I'm a little lost on what I'm doing wrong.

Can anyone point me in the right direction?


Solution

  • Your immediate problem is that you're setting the variable to the value < "Two"> which you can see here:

    @echo off
    
    SETLOCAL ENABLEDELAYEDEXPANSION
    
    ::Observe variable is not defined
    SET test
    
    ::Define initial value
    SET test = "Two"
    
    ::Observe initial value is set
    SET test
    echo %test%
    echo..%test %.
    
    ::Verify if the contents of the variable matches our condition
    If "!test!" == "Two" GOTO TWO
    
    ::First Place holder
    :ONE
    
    ::Echo first response
    ECHO "One"
    
    ::Second Place holder
    :TWO
    
    ::Echo second response
    ECHO "Two"
    
    ::Await user input
    PAUSE
    
    ENDLOCAL
    

    which produces:

    Environment variable test not defined
    test = "Two"
    . "Two".
    "One"
    "Two"
    Press any key to continue . . .
    

    The reason your "set test" is outputting the variable is the same reason why "set t" would - if there's no variable of the specific name, it outputs all variables starting with that name.

    The set command is also a finicky little beast and does not like spaces surrounding the '=' characters; it incorporates them (and the quotes by the way) into the environment variable name and the value assigned to it. Instead, use:

    set test=Two
    

    Also, where you're using delayed expansion, it doesn't matter since %test% and !test! would expand the same. It's useful in statements like:

    if "!test!" == "Two" (
        set test=TwoAndABit
        echo !test!
    )
    

    The inner echo will output TwoAndABit whereas %test%, which is expanded when the whole if-statement is encountered, would cause it to output Two.

    Still, I always use delayed expansion everywhere just for consistency.