批处理文件中的延迟扩展示例 [英] Example of delayed expansion in batch file

查看:148
本文介绍了批处理文件中的延迟扩展示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以告诉我一个批处理脚本在延迟扩展或没有延迟扩展的情况下会有什么不同吗?有什么情况下你不想使用延迟扩展?感谢。

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.

推荐答案

查看以下示例...

示例1:以下代码不使用延迟展开,因此for循环中的变量只会展开一次。这意味着在循环的每次迭代中,%Count%将总是扩展为 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

因此,此脚本将输出:

Count = 0
Count = 0
Count = 0
Count = 0

这不是这个循环应该如何工作。

This is not how this loop is supposed to work.

示例2:我们使用延迟扩展,我们有以下脚本,它将按预期运行。

Example 2: On the other hand, if we use delayed expansion, we have the following script, which 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

,并且如预期的那样, p>

and, as expected, it will output:

Count = 1
Count = 2
Count = 3
Count = 4

使用 ENABLEDELAYEDEXPANSION code>!而不是,每次重新展开变量,一切都按原样工作。

When you use the ENABLEDELAYEDEXPANSION, and expand a variable using ! instead of %, the variable is re-expanded each time, and everything works as it's supposed to.

这篇关于批处理文件中的延迟扩展示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆