Search code examples
shellfor-loopwindows-shell

Windows shell nested for loops


I wanted to run a program several times with two increasing input parameters. For this purpose I had to write a small shell script containing two nested for loops. For some reason, that I didn't understood the script stops its execution before printing all values.

for /l %%r in (1 2 3 4 5 6 7 8 9 10) do (
    for /l %%c in (1 2 3 4 5 6 7 8 9 10) do (
        rem Run my program here!
        echo %%r %%c 
    )
)

The output is

1 1
1 3
3 1
3 3

I'm really lost, as I'm no expert in windows shell programming.


Solution

  • You have added the /l flag, which has the following properties:

    for /l %%X in (start, step, end) do command
    

    So in your case:

    Start: 1
    Step : 2
    End  : 3
    

    So thats why you get:

    (1, 1), (1,3), (3,1), (3,3)
    

    If you remove the /l you should get the results as expected.

    echo off
    for  %%r in (1 2 3 4 5 6 7 8 9 10) do (
        for  %%c in (1 2 3 4 5 6 7 8 9 10) do (
            echo %%r %%c 
        )
    )
    

    Which returns (1,1) to (10,10).

    You can find more information here