Windows Batch files: what is variable expansion, and what does EnableDelayedExpansion mean?

后端 未结 2 2036
北海茫月
北海茫月 2020-11-29 06:39

What is meant by \"variable expansion\"? Does it mean simply \"variable definition\", or something else?

What happens when I say setLocal EnableDelayedExpansio

2条回答
  •  醉梦人生
    2020-11-29 07:34

    • Variable expansion means replace a variable enclosed in % or ! by its value.
    • The %normal% expansion happen just once, before a line is executed. This means that a %variable% expansion have the same value no matters if the line is executed several times (like in a for command).
    • The !delayed! expansion is performed each time that the line is executed.

    See this example:

    @echo off
    setlocal EnableDelayedExpansion
    set "var=Original"
    set "var=New" & echo Normal: "%var%", Delayed: "!var!"
    

    Output:

    Normal: "Original", Delayed: "New"
    

    Another one:

    @echo off
    setlocal EnableDelayedExpansion
    set "var1=Normal"
    set "var2=Delayed"
    for /L %%i in (1,1,10) do (
       set "var1=%var1% %%i"
       set "var2=!var2! %%i"
    )
    echo Normal:  "%var1%"
    echo Delayed: "%var2%"
    

    Output:

    Normal:  "Normal 10"
    Delayed: "Delayed 1 2 3 4 5 6 7 8 9 10"
    

    Normal expansion is not necessarily a disadvantage, but depends on the specific situation it is used. For example, in any other programming languages, to exchange the value of two variables you need the aid of a third one, but in Batch it can be done in just one line:

    set "var1=%var2%" & set "var2=%var1%"
    

提交回复
热议问题