简体   繁体   English

在bash脚本中创建嵌套的for循环

[英]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循环,该循环的计数从1到10,第二个或嵌套的循环的计数从1到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 谢谢

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 : 这使用整数除法从$i的值中减去5的正确倍数:

  • when $i is between 1 and 5, (i-1)/5 is 0 , so nothing is subtracted $i在1到5之间时, (i-1)/50 ,所以不减去任何东西
  • when $i is between 6 and 10, (i-1)/5 is 1 , so 5 is subtracted $i在6到10之间时, (i-1)/51 ,因此减去5

etc. 等等

You must not use a nested loop in this case. 在这种情况下,您不能使用嵌套循环。 What you have is a second co-variable, ie 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 : 这意味着你可以计算出的值ai

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 . %5将确保该值始终在0到4之间。这意味着我们需要i从0到9运行,这使我们得到i-1 Afterwards, we need to move 0...4 to 0...5 with +1 . 然后,我们需要使用+1将0 ... 4移到0 ... 5。

I know @AaronDigulla's answer is what OP wants. 我知道@AaronDigulla的答案是OP想要的。 this is another way to get the output :) 这是获取输出的另一种方法:)

paste -d':' <(seq 10) <(seq 5;seq 5)
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 如果您确实需要使用2个循环,请尝试

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM