gpt4 book ai didi

batch-file - SETLOCAL 和 ENABLEDELAYEDEXPANSION 如何工作?

转载 作者:行者123 更新时间:2023-12-03 06:11:49 24 4
gpt4 key购买 nike

我注意到在大多数脚本中,两者通常位于同一行,如下所示:

SETLOCAL ENABLEDELAYEDEXPANSION

这两个实际上是独立的命令并且可以写在不同的行上吗?

如果在脚本的第一行设置ENABLEDELAYEDEXPANSION,并且直到脚本结束才禁用它,是否会对脚本产生不利影响?

最佳答案

我想你应该明白什么是延迟扩展。恕我直言,现有的答案并没有(充分)解释它。

输入 SET/? 很好地解释了这一点:

Delayed environment variable expansion is useful for getting around the limitations of the current expansion which happens when a line of text is read, not when it is executed. The following example demonstrates the problem with immediate variable expansion:

set VAR=before
if "%VAR%" == "before" (
set VAR=after
if "%VAR%" == "after" @echo If you see this, it worked
)

would never display the message, since the %VAR% in BOTH IF statements is substituted when the first IF statement is read, since it logically includes the body of the IF, which is a compound statement. So the IF inside the compound statement is really comparing "before" with "after" which will never be equal. Similarly, the following example will not work as expected:

set LIST=
for %i in (*) do set LIST=%LIST% %i
echo %LIST%

in that it will NOT build up a list of files in the current directory, but instead will just set the LIST variable to the last file found. Again, this is because the %LIST% is expanded just once when the FOR statement is read, and at that time the LIST variable is empty. So the actual FOR loop we are executing is:

for %i in (*) do set LIST= %i

which just keeps setting LIST to the last file found.

Delayed environment variable expansion allows you to use a different character (the exclamation mark) to expand environment variables at execution time. If delayed variable expansion is enabled, the above examples could be written as follows to work as intended:

set VAR=before
if "%VAR%" == "before" (
set VAR=after
if "!VAR!" == "after" @echo If you see this, it worked
)

set LIST=
for %i in (*) do set LIST=!LIST! %i
echo %LIST%

另一个例子是这个批处理文件:

@echo off
setlocal enabledelayedexpansion
set b=z1
for %%a in (x1 y1) do (
set b=%%a
echo !b:1=2!
)

这将打印 x2y2:每个 1 都会被 2 替换。

如果没有setlocalenabledelayedexpansion,感叹号就是这样,所以它会回显!b:1=2!两次。

由于读取( block )语句时会扩展普通环境变量,因此扩展 %b:1=2% 使用值 b 在循环之前有:z2(但未设置时为y2)。

关于batch-file - SETLOCAL 和 ENABLEDELAYEDEXPANSION 如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6679907/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com