Why is delayed expansion in a batch file not working in this case?

后端 未结 3 1292
南笙
南笙 2020-12-04 00:26

This code

@echo off
setlocal EnableDelayedExpansion

set myvar=first
set first=second

echo myvar:!myvar!
set myvar=!myvar!
echo myvar:!myvar!
3条回答
  •  借酒劲吻你
    2020-12-04 00:51

    What you're trying to do won't work - delayed expansion only changes the variable expansion behavior of a variable inside of a block. It doesn't allow you the aliasing/nesting (for a lack of a better word) that you are attempting.

    set myvar=first sets the variable myvar to the text "first". set first=second sets the variable first to the text "second. There is no link between those two lines. myvar will never evaluate to something that it wasn't explicitly set to.

    I don't believe there is anyway to accomplish what you are trying to do here.


    * Edit *

    OK after taking a look at your answer I seeing how that works, you can get your desired output with this:

    @echo off
    setlocal EnableDelayedExpansion
    
    set myvar=first
    set first=second
    
    echo myvar:%myvar%
    set myvar=!%myvar%!
    echo myvar:%myvar%
    

    So the magic seems to happen because of the way that standard and delayed expansion occur. The line set myvar=!%myvar%! is seems be expanded first by the standard expander to set myvar=!first! (you'll see this if you run the script with echo on). Then the delayed expander runs and expands !first to "second" and set's myvar to that.

    I have no idea if this is documented behavior as to how standard and delayed expansion should work or just an implementation detail (which means it could break in the future)

提交回复
热议问题