views:

653

answers:

3

Is it possible in 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 sintax.

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

Thanks!

+1  A: 
FOR /r %X IN (*.txt) DO (ECHO %X & DEL %X)
SilverSkin
It works, thanks!
Marco Demajo
bk1e
+3  A: 

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, run if /?|find /V "" for the details

Anders
+2  A: 

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
bk1e
While we are on the topic, %X is never correct when dealing with filenames, always use "%~X" (In your example here, you could get away with using %* in the subfunction probably)
Anders
That's a really good point. A good example of a path that demonstrates both problems is `C:\Program Files (x86)`.
bk1e