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

后端 未结 2 2030
北海茫月
北海茫月 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:20

    In batch variables are expanded by enclosing them in percent signs.

    set myVariable=Hello world
    echo %myVariable%
    

    That means variable expansion.

    Compared to other programming languages, batch don't really work with variables.
    Normally it works only with the expansion of them.
    It works like the macro expansion of C/C++.

    So there doesn't exist a string length function to get the length of a variable,
    but you can write a function that counts the characters of text.

    Explanation of setLocal EnableDelayedExpansion
    The normal percent expansion has two disadvantages.

    The expansion happens in the moment of the parsing of a line or a block enclosed with parenthesis, not when the block is executed.

    Lets see this sample

    set var=one
    
    set var=two & echo %var%
    echo %var%
    

    The output will be

    one
    two

    As the echo %var% will be expand before the set var=two will be executed. This can get problematic in FOR loops.

    And the second disadvantage is that the batch parser will parse the expanded result of the variable.

    set var=cat^&dog
    echo %var%
    

    var
    Unknown command "dog"

    But the percent expansion exists since the beginning of MS-Dos (1920 or so).

    The DelayedExpansion adds a new expansion character, the exclamation mark !.

    But you have to active it first to use it with setlocal EnableDelayedExpansion, this is for compatibility reasons to old programs.

    setlocal EnableDelayedExpansion
    set var=one
    set var=two & echo !var!
    set var=cat^&dog
    echo !var!
    

    two
    cat&dog

    So this solves both problems of the percent expansion.

    Delayed Expansion on the command line
    You can't enable it by setlocal EnableDelayedExpansion, on the command line it has no effect at all.
    But you can use cmd /v:on

    set "var=Cat & dog" & cmd /V:on /c echo !var!
    

提交回复
热议问题