Nested batch for loops Nested batch for loops windows windows

Nested batch for loops


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

@echo offSetLocalset B=alpha beta gammaset A=eins zwoFOR %%b in (%B%) do (  FOR %%a in (%A% %%b) DO (    echo %%b -^> %%a  ))

The output (at least on Windows 7) is

alpha -> einsalpha -> zwoalpha -> alphabeta -> einsbeta -> zwobeta -> betagamma -> einsgamma -> zwogamma -> gamma

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


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

@echo offset TESTDIRS=fast mid slowset TD=src\test\resources\testsuitefor %%d in (%TESTDIRS%) do call :process_testdir %%dgoto :eof:process_testdirset CTD=%TD%\%1echo CTD: %CTD%    REM Echos the expected pathfor /R %CTD% %%f in (*.fs) do (echo %%f)    REM Echos as expectedgoto :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.


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