简体   繁体   English

为什么FOR loop命令在Windows命令提示符下可以工作的批处理文件中不起作用?

[英]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.

相关问题 脚本批处理不适用于.bat文件,但如果在命令提示符下编写,则可以使用 - Script batch does not work in a .bat file, but works if written in a command prompt 为什么“启动firefox”命令在Windows命令提示符下有效? - Why does “start firefox” command works in Windows command prompt? 命令在命令提示符中有效,但在批处理文件中无效 - Command works in Command Prompt but not in a batch file 为什么此wmic命令在批处理文件中不起作用 - Why does this wmic command not work in a batch file Windows上批处理文件和命令提示符之间的区别 - Differences between batch file and command prompt on windows Windows 带查找命令的批处理 for 循环在包含大量文件的文件夹中不起作用 - Windows batch for loop with find command does not work in a folder with a lot of files Windows命令提示符为什么可以运行此文件? - Why can Windows command prompt run this file? 为什么批处理文件中的“超时”命令突然不再起作用? - Why does the command “Timeout” in a batch file suddenly not work anymore? 在执行长批处理文件时,为什么Windows命令提示符会停顿直到按下某个键? - Why does Windows command prompt stall until a key is pressed when executing long batch files? Python程序可在命令提示符下运行,但在Windows中打开时不起作用 - Python program works from command prompt but does not work when opened in Windows
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM