开发者

Windows batch: call more than one command in a FOR loop?

开发者 https://www.devze.com 2022-12-20 12:45 出处:网络
Is it possible in Windows batch file to call more than one command in a single 开发者_开发问答FOR loop? Let\'s say for example I want to print the file name and after delete it:

Is it possible in Windows batch file to call more than one command in a single 开发者_开发问答FOR loop? Let's say for example I want to print the file name and after delete it:

@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?


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.

See if /?|find /V "" for details.


FOR /r %%X IN (*) DO (ECHO %%X & DEL %%X)


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)).

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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号