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

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

问题描述

有人能给我一个例子,说明在有或没有延迟扩展的情况下,批处理脚本的行为会有所不同吗?是否存在您不想使用延迟扩展的情况?谢谢.

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

并且,正如预期的那样,它将输出:

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 of %, the variable is re-expanded each time, and everything works as it's supposed to.

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

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