matteo
matteo

Reputation: 3067

Nested c-style loops in bash

Can anybody explain why the following c-style loop in a bash script doesn't work as expected?

Script:

for ((i=0; i<3; i++))
do
    for ((j==0; j<3; j++))
    do
        echo "Iteration $i $j"
    done
done

Expected output:

Iteration 0 0
Iteration 0 1
Iteration 0 2
Iteration 1 0
Iteration 1 1
Iteration 1 2
Iteration 2 0
Iteration 2 1
Iteration 2 2

Observed output:

Iteration 0
Iteration 0 1
Iteration 0 2

This makes no sense to me. I guess the inner and outer loop "interfere" somwhow (very weirdly) with each other. Non-c-style for loops (with "in") do work as expected...

thanks m.

Upvotes: 0

Views: 845

Answers (2)

vabh
vabh

Reputation: 44

yes, its because you wrote j==0 . hence only 1 iteration of the inner loop happens, because once j++ makes the value of j equal to 1, the equality j==0 is no longer true.

Upvotes: 2

basti
basti

Reputation: 2689

for ((j==0; j<3; j++))

is this a typo just here, or do you really test j for equality to 0? That would maybe explain it...

Upvotes: 1

Related Questions