for loop with multiple conditions in Bash scripting

老子叫甜甜 提交于 2020-02-28 06:31:07

问题


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.

In C, I'd do:

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.


回答1:


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:

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.




回答2:


There is not a big difference if you compare it with C

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


来源:https://stackoverflow.com/questions/10342184/for-loop-with-multiple-conditions-in-bash-scripting

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!