问题描述
有人可以给我在那里一个批处理脚本将有或无延迟扩展不同作用的例子吗?在那里,你不会想使用延迟扩展的情况呢?谢谢你。
Can someone give me an example of where a batch script would act differently with or without delayed expansion? Are there any situations where you would NOT want to use delayed expansion? Thanks.
推荐答案
请看下面的例子...
Look at the following examples...
例1:以下code不使用延迟扩展,所以在循环展开仅一次的变量。这意味着%计数%
总会扩大到 0
在每次循环,不管我们做什么它与set命令:
Example 1: The following code DOESN'T use delayed expansion, so the variables in the for loop are expanded only one time. This means that %Count%
will always expand to 0
in each iteration of the loop, no matter what we do to it with the set command:
@echo off
set COUNT=0
for %%v in (1 2 3 4) do (
set /A COUNT=%COUNT% + 1
echo Count = %COUNT%
)
pause
所以,这个脚本将输出:
So this script will output:
Count = 0
Count = 0
Count = 0
Count = 0
这是不是这个循环应该是怎样工作的。
This is not how this loop is supposed to work.
例2:,然后,如果我们用延迟的扩展,我们有以下的脚本,这会按预期运行
Example 2: Then, if we use delayed expansion, we have the following script, this will run as expected.
setlocal ENABLEDELAYEDEXPANSION
set COUNT=0
for %%v in (1 2 3 4) do (
set /A COUNT=!COUNT! + 1
echo Count = !COUNT!
)
pause
和,一如预期,这将输出:
and, as expected, it will output:
Count = 1
Count = 2
Count = 3
Count = 4
当您使用 ENABLEDELAYEDEXPANSION
,并使用扩展变量!
而不是%
,该变量每次都重新扩大,一切正常,因为它应该。
When you use the ENABLEDELAYEDEXPANSION
, and expand a variable using !
instead that %
, the variable is re-expanded each time, and everything works as it supposed to.
这篇关于在批处理文件延迟扩展的例子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!