简体   繁体   中英

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.

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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