Windows Batch file processing - Loops

前端 未结 2 1717
后悔当初
后悔当初 2020-12-21 15:10

Am very new to batch scritping. I just tried to execute the below code for which am totally confused.

@echo off
set m=100
set i=0
FOR /L %%N IN (0,1,%m%)do (         


        
相关标签:
2条回答
  • 2020-12-21 15:32

    In batch files, variable reads are replaced with their values at parse time, before executing the line or the block (code enclosed in parenthesis).

    So, the %i% reference inside the for loop is replaced with the value of the variable before the for loop, that is, 0 , and %m% is replaced with 100, and what gets executed is

    for /l %%n in (0 1 100) do ( set /a i=1+0 )
    

    You can enable delayed expansion (setlocal enabledelayedexpansion command) and change the sintax from %i% to !i! to indicate the parser that reads to the variable should be delayed until the moment of executing the line. The code should be

    @echo off
      setlocal enabledelayedexpansion
      set m=100
      set i=0
      FOR /L %%N IN (0,1,%m%)do (
        set /a i=1+!i!
      )
      echo %i%
      endlocal
    

    The read of the value of i inside the for loop is delayed. This way, the real value is readed just before each execution of the line. Reference to i out of the loop does not need it. When the line is reached and parsed, the correct value is retrieved and echoed.

    Anyway, while this is the general rule, set /a has a different behaviour. If you change your code to

    set /a i+=1
    

    or

    set /a i=i+1
    

    the parser will correctly identify the operation and execute the expected code with or without delayed expansion enabled.

    0 讨论(0)
  • 2020-12-21 15:43

    You need delayed expansion : http://www.robvanderwoude.com/variableexpansion.php

    @echo off
    setlocal enableDelayedExpansion
     set m=100
     set i=0
     FOR /L %%N IN (;;0,1,%m%;;) do (
       set /a i=1+!i!
     )
    endlocal & set /a i=%i%
    echo %i%
    
    0 讨论(0)
提交回复
热议问题