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.
A nested loop means a loop statement inside another loop statement. That is why nested loops are also called “loop inside loops“. We can define any number of loops inside another loop.
Use double percent signs ( %% ) to carry out the for command within a batch file. Variables are case sensitive, and they must be represented with an alphabetical value such as %a, %b, or %c. ( <set> ) Required. Specifies one or more files, directories, or text strings, or a range of values on which to run the command.
If a loop exists inside the body of another loop, it's called a nested loop. Here's an example of the nested for loop. // outer loop for (int i = 1; i <= 5; ++i) { // codes // inner loop for(int j = 1; j <=2; ++j) { // codes } .. } Here, we are using a for loop inside another for loop.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With