Nested batch for loops
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.
What if you used pushd !CTD! and popd, and let FOR /R default to using the current directory?
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).