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

WindowsBatch FileCmd

Windows Problem Overview


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?

Windows Solutions


Solution 1 - Windows

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.

Solution 2 - Windows

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

Solution 3 - Windows

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMarco DemaioView Question on Stackoverflow
Solution 1 - WindowsAndersView Answer on Stackoverflow
Solution 2 - WindowsKalleView Answer on Stackoverflow
Solution 3 - Windowsbk1eView Answer on Stackoverflow