[英]Why does FOR loop command not work in a batch file which works on Windows command prompt?
FOR /L %A IN (1,1,100) DO echo %A
The code above in a batch script results in this error: 批处理脚本中的上述代码导致此错误:
A was unexpected at this time.
此时A是意外的。
The same command line works fine on Windows command prompt. 相同的命令行在Windows命令提示符下工作正常。
What is the problem? 问题是什么?
您需要使用双百分比字符:
FOR /L %%A IN (1,1,100) DO echo %%A
The problem is with %
, %A
is for use on command lines only. 问题出在
%
, %A
仅用于命令行。
when used in batch files %A
should be substituted with %%A
. 在批处理文件中使用时,应将
%A
替换为%%A
。
If you run FOR /?
如果运行
FOR /?
you'll find that the first paragraph after the parameter list starts as follows: 您会发现参数列表之后的第一段如下所示:
To use the FOR command in a batch program, specify %%variable instead of %variable.
要在批处理程序中使用FOR命令,请指定%% variable而不是%variable。
As an example, let's start with a simple FOR
loop: 例如,让我们从一个简单的
FOR
循环开始:
FOR %x in (*) DO ECHO %x
This will run just fine from a command prompt, printing out the name of each file in the current directory, but if we use this verbatim in a Batch file, we'll get an error saying this: 这将在命令提示符下正常运行,打印出当前目录中每个文件的名称,但如果我们在批处理文件中使用此逐字记录,则会收到一条错误消息:
x was unexpected at this time.
x此时是意外的。
This is because Batch files have some extra abilities that use the percent sign immediately followed by some text, so when FOR
is called from inside a Batch file it instead looks for two percent signs. 这是因为批处理文件具有一些额外的功能,这些功能会立即使用百分号后跟一些文本,因此从批处理文件内部调用
FOR
时,它会查找两个百分号。 So if we want to use that same FOR
loop in a Batch script, we need to replace each instance of %x
with %%x
. 因此,如果要在批处理脚本中使用相同的
FOR
循环,则需要将%x
每个实例替换为%%x
。
What we end up putting in our Batch file is this: 我们最终放入批处理文件中的内容是这样的:
FOR %%x in (*) DO ECHO %%x
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.