Windows 批处理:在 FOR 循环中调用多个命令?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2252979/
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
Windows batch: call more than one command in a FOR loop?
提问by Marco Demaio
Is it possible in Windows batch file to call more than one command in a singleFOR
loop? Let's say for example I want to print the file name and after delete it:
在 Windows 批处理文件中是否可以在单个FOR
循环中调用多个命令?假设例如我想打印文件名并在删除它之后:
@ECHO OFF
FOR /r %%X IN (*.txt) DO (ECHO %%X DEL %%X)
REM the line above is invalid syntax.
I know in this case I could solve it by doing two distinct FOR loops: one for showing the name and one for deleting the file, but is it possible to do it in one loop only?
我知道在这种情况下,我可以通过执行两个不同的 FOR 循环来解决它:一个用于显示名称,另一个用于删除文件,但是否可以仅在一个循环中执行此操作?
采纳答案by SilverSkin
FOR /r %%X IN (*) DO (ECHO %%X & DEL %%X)
回答by Anders
Using &
is fine for short commands, but that single line can get very long very quick. When that happens, switch to multi-line syntax.
使用&
短命令很好,但是单行可以很快变得很长。发生这种情况时,请切换到多行语法。
FOR /r %%X IN (*.txt) DO (
ECHO %%X
DEL %%X
)
Placement of (
and )
matters. The round brackets after DO
must be placed on the same line, otherwise the batch file will be incorrect.
安置(
和)
事项。后面的圆括号DO
必须放在同一行,否则批处理文件会出错。
See if /?|find /V ""
for details.
详情请参阅if /?|find /V ""
。
回答by bk1e
SilverSkin and Anders are both correct. You can use parentheses to execute multiple commands. However, you have to make sure that the commands themselves (and their parameters) do not contain parentheses. cmd
greedily searches for the first closing parenthesis, instead of handling nested sets of parentheses gracefully. This may cause the rest of the command line to fail to parse, or it may cause some of the parentheses to get passed to the commands (e.g. DEL myfile.txt)
).
SilverSkin 和 Anders 都是正确的。您可以使用括号来执行多个命令。但是,您必须确保命令本身(及其参数)不包含括号。cmd
贪婪地搜索第一个右括号,而不是优雅地处理嵌套的括号集。这可能会导致命令行的其余部分无法解析,或者可能会导致某些括号被传递给命令(例如DEL myfile.txt)
)。
A workaround for this is to split the body of the loop into a separate function. Note that you probably need to jump around the function body to avoid "falling through" into it.
解决方法是将循环体拆分为单独的函数。请注意,您可能需要绕过函数体以避免“落入”其中。
FOR /r %%X IN (*.txt) DO CALL :loopbody %%X
REM Don't "fall through" to :loopbody.
GOTO :EOF
:loopbody
ECHO %1
DEL %1
GOTO :EOF