variables expansion inside for in batch

前端 未结 2 1106
暗喜
暗喜 2020-12-12 05:36

I am new to batch and I don\'t understand when to use late variable expansion or normal expansion. Below I have a test script in which I have tested the variables expansion.

相关标签:
2条回答
  • 2020-12-12 05:56

    When a line or a block of code (the code enclosed in parenthesis in your for, if, ... ) is reached, the parser removes all variable reads, replacing them with the value inside the variable before the line/block starts to execute. So, if the value of a variable is changed inside a line/block, this changed value is not visible inside that same line/block since all access to the variable content has been replaced with its value.

    So, if the value of the variable is changed inside a line/block AND the changed value of the variable needs to be read/accessed inside the same line/block, delayed expansion is needed.

    for and if commands are places where this is usually more evident, but constructs as

    set "data=test"
    ....
    set "data=other test" & echo %data%
    

    shows the same problem. When the parser handles the last line, %data% is replaced with its value, and then the line is executed. So the final line executed is

    set "data=other test" & echo test
    
    0 讨论(0)
  • 2020-12-12 06:01

    This can work depending on the text being parsed, as poison characters can affect it.

    @echo off
    set var=0
    echo late var=%var%
    echo var=%var%
    
    for /F "delims= " %%A in (temp.txt) do call :next "%%A"
    goto :EOF
    :next
            echo Analyzing %~1
            set line=%~1
            echo line=%line%
            echo late line=%line%
    
    0 讨论(0)
提交回复
热议问题