windows 为什么即使设置了这个批处理变量也永远不会改变?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3949978/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why does this batch variable never change even when set?
提问by jcao219
@echo off
SET first=0
FOR %%N IN (hello bye) DO (
SET first=1
echo %first%
echo %%N
)
It seems that the variable "first" is always 0. Why?
似乎变量“first”总是0。为什么?
回答by Michael Madsen
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.
使用批处理文件,变量在读取命令时会被扩展 - 这样就会在for
执行时立即展开。那时,它不再说echo %first%
,而是字面意思echo 0
,因为那是扩张点的价值。
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
).
为了解决这个问题,您需要使用延迟扩展,将您的变量名用!
而不是%
- 括起来,这样就可以了echo !first!
。这可能需要您使用 /V 参数启动 cmd.exe,或者setlocal enabledelayedexpansion
在批处理文件的开头使用(紧跟在 之后echo off
)。
If you type set /?
, you'll see a much more detailed explanation of this at the end of the output.
如果您键入set /?
,您将在输出的末尾看到更详细的解释。