简体   繁体   English

在Bash脚本中具有多个条件的for循环

[英]for loop with multiple conditions in Bash scripting

It's been a while since I've done intense bash scripting and I forgot the syntax for doing multiple conditions in a for loop. 我已经有一段时间了,因为我已经完成了强烈的bash脚本编写,我忘记了在for循环中执行多个条件的语法。

In C, I'd do: 在C中,我会这样做:

for(var i=0,j=0; i<arrayOne.length && j<arrayTwo.length; i++,j++){
  // Do stuff
}

I've been googling for a while and have only found syntax involving nested for loops, not multiple conditions to one for loop. 我已经谷歌搜索了一段时间,只发现涉及嵌套for循环的语法,而不是一个for循环的多个条件。

Sounds like you're talking about the arithmetic for loop . 听起来你在谈论循环算法

for ((i = j = 0; i < ${#arrayOne[@]} && j < ${#arrayTwo[@]}; i++, j++)); do
    # Do stuff
done

Which assuming i and j are either unset or zero is approximately equivalent to: 假设ij未设置或为零,大致相当于:

while ((i++ < ${#arrayOne[@]} && j++ < ${#arrayTwo[@]})); do ...

and slightly more portable so long as you don't care about the values of i / j after the loop. 只要你不关心循环后i / j的值,就可以稍微提高一点。

There is not a big difference if you compare it with C 如果将它与C进行比较,则没有太大区别

for (( c=1,d=1; c<=5 && d<=6; c++,d+=2 ))
do
        echo "$c : $d"
done

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

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