Windows Batch file processing - Loops

匿名 (未验证) 提交于 2019-12-03 02:03:01

问题:

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 ( set /a i=1+%i% )

echo %i% pause

Here, am incrementing i value until N reaches 100. So, am expecting the value of i at the end of loop to be 101 but it shows 1. Can anyone explain what's the reason behind this.

thanks

回答1:

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%


回答2:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!