Scott Pearce
Scott Pearce

Reputation: 207

Creating a nested for loop in bash script

I am trying to create a nested for loop which will count from 1 to 10 and the second or nested loop will count from 1 to 5.

for ((i=1;i<11;i++));
do
     for ((a=1;a<6;a++));
     do
         echo $i:$a
     done
done

What I though the output of this loop was going to be was:

1:1
2:2
3:3
4:4
5:5
6:1
7:2
8:3
9:4
10:5

But instead the output was

1:1
1:2
1:3
1:4
1:5
2:1
...
2:5
3:1
...
and same thing till 10:5

How can I modify my loop to get the result I want! Thanks

Upvotes: 0

Views: 129

Answers (4)

Degustaf
Degustaf

Reputation: 2670

a=0
for ((i=1;i<11;i++))
do
    a=$((a%5))
    ((a++))
    echo $i:$a
done

If you really need it to use 2 loops, try

for ((i=1;i<3;i++))
do
    for ((a=1;a<6;a++))
    do
        echo "$((i*a)):$a"
    done
done

Upvotes: 0

Farvardin
Farvardin

Reputation: 5414

I know @AaronDigulla's answer is what OP wants. this is another way to get the output :)

paste -d':' <(seq 10) <(seq 5;seq 5)

Upvotes: 1

Tom Fenech
Tom Fenech

Reputation: 74596

Your logic is wrong. You don't want a nested loop at all. Try this:

for ((i=1;i<11;++i)); do
    echo "$i:$((i-5*((i-1)/5)))"
done

This uses integer division to subtract the right number of multiples of 5 from the value of $i:

  • when $i is between 1 and 5, (i-1)/5 is 0, so nothing is subtracted
  • when $i is between 6 and 10, (i-1)/5 is 1, so 5 is subtracted

etc.

Upvotes: 3

Aaron Digulla
Aaron Digulla

Reputation: 328556

You must not use a nested loop in this case. What you have is a second co-variable, i.e. something that increments similar to the outer loop variable. It's not at all independent of the outer loop variable.

That means you can calculate the value of a from i:

for ((i=1;i<11;i++)); do
    ((a=((i-1)%5)+1))
    echo $i:$a
done

%5 will make sure that the value is always between 0 and 4. That means we need i to run from 0 to 9 which gives us i-1. Afterwards, we need to move 0...4 to 0...5 with +1.

Upvotes: 1

Related Questions