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.

1
  • I'm new to batch programming (though steeped in bash), and would have never in my entire life have intuited that variables set inside for loops require !! to express their values... Commented Feb 14, 2023 at 21:51

6 Answers 6

38

Just to give an example of a nested loop that works:

@echo off
SetLocal

set B=alpha beta gamma
set A=eins zwo

FOR %%b in (%B%) do (
  FOR %%a in (%A% %%b) DO (
    echo %%b -^> %%a
  )
)

The output (at least on Windows 7) is

alpha -> eins
alpha -> zwo
alpha -> alpha
beta -> eins
beta -> zwo
beta -> beta
gamma -> eins
gamma -> zwo
gamma -> gamma

This supports jeb's observation that variable expansion in loops works if they occur inside parenthesis (even without delayed expansion).

Sign up to request clarification or add additional context in comments.

2 Comments

hi i used your example but it will print %%b instead of %%a in the last steep,i solved it by using just FOR %%a in (%A%) in the inner loop
@JuanAntonioOrozco You might have observed the intended behaviour. I edited my answer to clarify what the loop should print.
17

Because nobody has mentioned it, here is the solution using batch subroutines and the CALL command.

@echo off

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

for %%d in (%TESTDIRS%) do call :process_testdir %%d
goto :eof

:process_testdir
set CTD=%TD%\%1
echo CTD: %CTD%
    REM Echos the expected path

for /R %CTD% %%f in (*.fs) do (echo %%f)
    REM Echos as expected

goto :eof

I know GOTO is not very popular, but batch files were originally designed to use labels for control flow. The parenthetized control structure syntax was added later, and this question is an example of where it breaks down. The problem lends itself well to batch subroutines.

Comments

9

What if you used pushd !CTD! and popd, and let FOR /R default to using the current directory?

2 Comments

I'll accept this solution since it solves the question in the context of my example. And it's really clever :-)
This is a workaround that solves the specific problem differently. It doesn't explain how to correctly nest for-loops (i.e. doesn't answer the question). I want to nest for-loops with a different use-case in which this workaround doesn't solve the problem and came here via google search for "batch nested for loop". -1 from me.
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.

2 Comments

Sorry, but I don't see how your reply helps me with my question since it only tells me what doesn't work. In addition, I already mentioned in my question that I am aware of the possibility of replacing the inner loop with a subroutine but my question was how to make the nested loop work.
Sorry, but I suppose you can only use the PUSHD solution from Ben Voigt. With expansion it seems to be impossible, because the path for the inner loop is expanded only one, at the beginning of the first parenthesis,
1

Quote Malte Schwerhoff's Answer

If you don't want to repeat B, you can simply add "if" statement

@echo off
SetLocal

set B=alpha beta gamma
set A=eins zwo

FOR %%b in (%B%) do (
  FOR %%a in (%A% %%b) DO (
    IF %%b NEQ %%a (
        echo %%b -^> %%a
    )
  )
)

output:

alpha -> eins
alpha -> zwo
beta -> eins
beta -> zwo
gamma -> eins
gamma -> zwo

Comments

0

According to FOR help, FOR /R "Walks the directory tree rooted at [drive:]path, executing the FOR statement in each directory of the tree."

What may be at issue is the word 'walk'. It seems to me that a walk doesn't occur until one takes the first step and if no step occurs then no walk occurs. Since in this case the walk begins in directory 'fast' and there are no subdirectories, no first step is possible.

However, if you change the second FOR to:

for /R !CTD!\..\ %%f in (*.fs) do (echo %%f)

then the result echoed is:

CTD: src\test\resources\testsuite\fast
CTD:
C:\FORTEST\src\test\resources\testsuite\fast\F1.fs
C:\FORTEST\src\test\resources\testsuite\mid\F2.fs
C:\FORTEST\src\test\resources\testsuite\slow\F3.fs
C:\FORTEST\src\test\resources\testsuite\fast\F1.fs
CTD: src\test\resources\testsuite\mid
CTD:
C:\FORTEST\src\test\resources\testsuite\fast\F1.fs
C:\FORTEST\src\test\resources\testsuite\mid\F2.fs
C:\FORTEST\src\test\resources\testsuite\slow\F3.fs
C:\FORTEST\src\test\resources\testsuite\fast\F1.fs
CTD: src\test\resources\testsuite\slow
CTD:
C:\FORTEST\src\test\resources\testsuite\fast\F1.fs
C:\FORTEST\src\test\resources\testsuite\mid\F2.fs
C:\FORTEST\src\test\resources\testsuite\slow\F3.fs
C:\FORTEST\src\test\resources\testsuite\fast\F1.fs

Is that what OP was looking 'FOR'? If so, it would be because now there is someplace to recurse from, that being the parent dir.

(Note: in this test the dirs fast, mid, slow contained one file each, F1.fs, F2.fs and F3.fs, respectively.)

1 Comment

This answer would include directories not in %TESTDIRS%. And as noted in the question, /R src\test\resources\testsuite\fast %%f works, which is the intended result of set CTD=%TD%\%%d, so the problem is not likely a misunderstanding of how the tree is being walked.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.