Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

for loop with multiple conditions in Bash scripting

Tags:

bash

for-loop

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.

like image 883
Miles Avatar asked Dec 16 '22 01:12

Miles


1 Answers

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.

like image 159
ormaaj Avatar answered Jan 04 '23 12:01

ormaaj