5

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.

2 Answers 2

10

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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

4 Comments

Well that's the C-style syntax and I haven't tried that. I was more interested in something like for i in $things; do .. done
if you have just one loop you can do it like this: x[0]="test 1"; x[1]="test 2"; for i in "${x[@]}"; do echo $i; done
for in iterates arguments. It doesn't have anything to do with "conditions" and can't do the equivalent of the c-style loop without nesting. for i in "${arrayOne[@]}" "${arrayTwo[@]}"; do would iterate the elements of each array sequentially.
That last part is the exact syntax I was looking for, but it's great to know the c style syntax. Thanks for the explanation @ormaaj. I'll mark you as the answer for that great comment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.