我有以下代码:
@echo off设置 ITER=0对于 (%*) 中的 %%i 做 (设置 ITER+=1回声%ITER%)输出是(对于三个参数):
000预期输出:
123为什么我不能在 for 循环中访问更新的变量?
解决方案在执行语句/块之前使用百分比扩展变量.因此,在您的情况下,在执行 echo %ITER% 之前将完整块扩展为常量 echo 0.变量 ITER 本身在循环中正确更新.
为了避免这种情况,您可以使用延迟扩展,这类似于百分比扩展,但只是在执行的那一刻
@echo offsetlocal EnableDelayedExpansion设置 ITER=0对于 (%*) 中的 %%i 做 (SET/a ITER+=1回声!ITER!)I have following code:
@echo off SET ITER=0 for %%i in (%*) do ( SET ITER+=1 ECHO %ITER% )The output is (for three arguments):
0 0 0Expected output:
1 2 3Why can't I access the updated variable in the for loop?
解决方案Expansion of variables with percents is done before a statement/block is executed. So in your case the complete block is expanded before the echo %ITER% is executed, to constant echo 0. The variable ITER itself is updated in the loop properly.
To avoid this, you could use the delayed expansion, this works like percent expansion but just in the moment of execution
@echo off setlocal EnableDelayedExpansion SET ITER=0 for %%i in (%*) do ( SET /a ITER+=1 ECHO !ITER! )
更多推荐
在“for"循环中使用变量
发布评论