Alex Rivera | Logout

Nested batch for loops

Asked 2010-12-02T10:59:44.727
34

The following nested for-loop drives me mad (on Windows 7):

@echo off
SetLocal EnableDelayedExpansion

set TESTDIRS=fast mid slow
set TD=src\test\resources\testsuite

for %%d in (%TESTDIRS%) do (
    set CTD=%TD%\%%d
    echo CTD: !CTD!
        REM Echos the expected path
    echo CTD: %CTD%
        REM Echos nothing -- understandable

    for /R !CTD! %%f in (*.fs) do (echo %%f)
        REM Echos nothing -- why?
    for /R src\test\resources\testsuite\fast %%f in (*.fs) do (echo %%f)
        REM Echos expected files
)

I tried various solutions involving disabling DelayedExpansion, call-statements and whatnot, but I never got the inner loop working. I know that I could replace the inner loop by a subroutine call, but there gotta be a way to make it work with nested loops.

Edit
Report

1 Answer

6

It's not obvious! It's the special parsing of FOR!
A FOR command is parsed directly after the escape/special character phase (for detecting the parenthesis), but as a result you can't using delayed or %%var expansion as parameters.

FOR %%a in (%%%%B) do (
  FOR %%a in (1) DO ( <<< this %%a will not replaced with %%B
      echo %%a - shows 1, because %%a is the name of the inner variable
      echo %%B - doesn't work
  )
)

And also this can't work:

set chars=abc
FOR /F "delims=!chars!" %%N in (bla) DO ....  

does not set a, b and c as delims, but !, c, h, a and r instead.

EDIT: Within the parentheses the delayed expansion does work as expected however:

set var=C:\temp
For %%a in (!var!) DO echo %%a

I would expect that you have to use a function to solve your problem.

answered 2010-12-02T13:36:45.057

Your Answer