Search code examples
bashshellubuntunested-loops

Nested For loop counter reset


I'm trying to run nested for loops that use lists as their loop counters. The problem is that once the 'delta' loop reaches 100, it doesnt reset to 0. Same problem for 'edges'.

I tried this, but it doesnt seem to work for my loops. http://tldp.org/LDP/abs/html/nestedloops.html

Any ideas here? Here's my code:

#!/bin/sh

threads="1 2 4 8 16 32 64 96 128 160 192 224 256"
delta="0 10 20 30 40 50 60 70 80 90 100"
edges="16 8192"
nodes="16384"

for threads in $threads
do
    for delta in $delta
    do
        for edges in $edges
        do
            for nodes in $nodes
            do
                printf "\n"
                echo $threads
                echo $delta
                echo $edges
                echo $nodes
            done
        done
    done
done

expected output:

1 0 16 16384 
1 0 8192 16384 
1 10 16 16384 
1 10 8192 16384 
1 20 16 16384 
1 20 8192 16384 

Solution

  • When using for loops like this, make sure you give the loop variable a different name than the variable you are iterating over.

    Using for threads in $threads makes it confusing to distinguish between the looping variable (threads) and the thing you're looping over ($threads).

    When you call echo $threads later, bash doesn't know you're referring to the first one.

    In this case, you could change the loop declarations to something like for n in nodes or for t in threads, then echo out $n and $t inside the innermost loop to obtain the desired output.