0

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

1
  • Note what you did is similar to echo {1..5}{1..5}. Commented Apr 22, 2015 at 15:26

4 Answers 4

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

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)

Comments

0
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

3 Comments

How would I get the same result if I want to use nested loop!
...well, actually I didn't do that, I used the correct syntax (it should be a=$((i%5)). Either way, the output is incorrect!
@TomFenech That is the single loop version I was trying to demonstrate

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.