Enable and Disable Delayed Expansion, what does it do?

后端 未结 4 1974
既然无缘
既然无缘 2020-12-02 23:55

I\'ve seen SETLOCAL ENABLEDELAYEDEXPANSION & SETLOCAL DISABLEDELAYEDEXPANSION in many batch files but what do the commands actually do?

相关标签:
4条回答
  • 2020-12-03 00:14

    Copied from How do you use SETLOCAL in a batch file? (as dbenham indicated in his first comment).

    Suppose this code:

    If "%getOption%" equ  "yes" (
       set /P option=Enter option: 
       echo Option read: %option%
    )
    

    Previous code will NOT work becase %option% value is replaced just one time when the IF command is parsed (before it is executed). You need to "delay" variable value expansion until SET /P command had modified variable value:

    setlocal EnableDelayedExpansion
    If "%getOption%" equ  "yes" (
       set /P option=Enter option: 
       echo Option read: !option!
    )
    

    Check this:

    set var=Before
    set var=After & echo Normal: %var%  Delayed: !var!
    

    The output is: Normal: Before Delayed: After

    0 讨论(0)
  • 2020-12-03 00:16

    enabledelayeexpansion instructs cmd to recognise the syntax !var! which accesses the current value of var. disabledelayedexpansion turns this facility off, so !var! becomes simply that as a literal string.

    Within a block statement (a parenthesised series of statements), the entire block is parsed and then executed. Any %var% within the block will be replaced by that variable's value at the time the block is parsed - before the block is executed - the same thing applies to a FOR ... DO (block).

    Using !var! in place of %var% accesses the changed value of var.

    0 讨论(0)
  • 2020-12-03 00:25

    ALSO note that with SETLOCAL ENABLEDELAYEDEXPANSION you cant echo !!!!!! so:

    echo my sentence! 123
    

    will be outputed as:

    my sentence 123

    0 讨论(0)
  • 2020-12-03 00:27

    With delayed expansion you will able to access a command argument using FOR command tokens:

    setlocal enableDelayedExpansion
    set /a counter=0
    for /l %%x in (1, 1, 9) do (
     set /a counter=!counter!+1
     call echo %%!counter! 
    )
    endlocal
    

    Can be useful if you are going to parse the arguments with for loops

    It helps when accessing variable through variable:

     @Echo Off
     Setlocal EnableDelayedExpansion
     Set _server=frodo
     Set _var=_server
     Set _result=!%_var%!
     Echo %_result%
    

    And can be used when checking if a variable with special symbols is defined:

    setlocal enableDelayedExpansion
    set "dv==::"
    if defined !dv! ( 
       echo has NOT admin permissions
    ) else (
       echo has admin permissions
    )
    
    0 讨论(0)
提交回复
热议问题