Batch file fails to set environment variable within conditional statement

后端 未结 3 1393

Why does the following Windows Batch File output Foo followedby Bar, rather than Baz?

@echo off
setlocal

set _=Foo
echo %         


        
相关标签:
3条回答
  • 2021-02-13 10:54

    The answer to this is the same as the answer to:Weird scope issue in batch file. See there for more details. Basically variable expansion is done at line read time, not at execution time.

    0 讨论(0)
  • 2021-02-13 10:57

    try this

    @echo off
    setlocal
    
    set _=Foo
    echo %_%
    set _=Bar
    if "1" NEQ "2" goto end
    set _=Baz
    echo %_%
    :end
    
    0 讨论(0)
  • 2021-02-13 11:03

    What's happening is that variable substitution is done when a line is read. What you're failing to take into account is the fact that:

    if 1==1 (
        set _=Baz
        echo %_%
    )
    

    is one "line", despite what you may think. The expansion of "%_%" is done before the set statement.

    What you need is delayed expansion. Just about every single one of my command scripts starts with "setlocal enableextensions enabledelayedexpansion" so as to use the full power of cmd.exe.

    So my version of the script would be:

    @echo off
    setlocal enableextensions enabledelayedexpansion
    
    set _=Foo
    echo !_!
    set _=Bar
    if 1==1 (
        set _=Baz
        echo !_!
    )
    
    endlocal
    

    This generates the correct "Foo", "Baz" rather than "Foo", "Bar".

    0 讨论(0)
提交回复
热议问题