为什么即使设置了这个批处理变量也永远不会改变? [英] Why does this batch variable never change even when set?
问题描述
@echo off
SET first=0
FOR %%N IN (hello bye) DO (
SET first=1
echo %first%
echo %%N
)
好像变量first"总是0,为什么?
It seems that the variable "first" is always 0. Why?
推荐答案
对于批处理文件,当读取命令时变量会被扩展 - 这样会在 for
执行后立即展开.那时,它不再说 echo %first%
,而是字面上的说 echo 0
,因为那是扩展点的值.
With batch files, variables are expanded when their command is read - so that would be as soon as the for
executes. At that point, it no longer says echo %first%
, it literally says echo 0
, because that was the value at the point of expansion.
要解决这个问题,您需要通过用 !
而不是 %
包围变量名称来使用延迟扩展 - 这样就可以 echo !first!代码>.这可能需要您使用/V 参数启动 cmd.exe,或者在批处理文件的开头使用
setlocal enabledelayedexpansion
(就在 echo off
之后).
To get around that, you need to use delayed expansion by surrounding your variable name with !
instead of %
- so that would be echo !first!
. This may require you to start cmd.exe with the /V parameter, or use setlocal enabledelayedexpansion
in the beginning of your batch file (just after echo off
).
如果你输入 set/?
,你会在输出的末尾看到更详细的解释.
If you type set /?
, you'll see a much more detailed explanation of this at the end of the output.
这篇关于为什么即使设置了这个批处理变量也永远不会改变?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!