Search code examples
batch-filefor-loopdelayexpansion

How to use delayed expansion with the iterator of the outer for-loop?


I cannot seem to find out, how I can use the iterator of the outer loop within the inner loop (in a batch file):

setlocal enabledelayedexpansion
REM for every folder in %mainfolder%
for /D %%s in (%mainfolder%\*) DO (
REM for every file in the subfolder %s
    for %%f in (%%s\*) do(
        some things with the files in that subfolder
    )
)

Where do I have to place the exclamation marks, so that I can actually use %s in the inner Loop? Right now, I get the Error

"do(" kann syntaktisch nicht an dieser stelle verarbeitet werden C:\fakepath> for %f in (%s*) do(

which means translated that "do(" cannot be syntactically processed at this position.

I am pretty sure that the problem actually has to do with the Delayed Expansion (actually, with not using it)


Solution

  • To correct the error, it is necessary to add a space between the do clause and the opening parenthesis of the code block.

    The %%s replaceable parameter scope/visibility is anywhere inside the for loop that initializes it. So, it can be directly used inside the inner loop.