Dave
Dave

Reputation: 4328

Why use seq 0 in bash for loop

Why use seq 0 in bash for loop?

for i in `seq 0 $(( ${#ARRAYEX[@]} - 1 ))`
do
    echo "ARRAYEX${i}=${ARRAYEX[${i}]}"
done

Upvotes: 3

Views: 9745

Answers (2)

Veger
Veger

Reputation: 37915

The seq command generates a sequence of numbers.

For example

seq 0 10

generates a sequence of numbers from 0 up to 10:

0 1 2 3 4 5 6 7 8 9 10

(usually each number is on a new line, but I place them after each other)

In your example a sequence on number starting at 0 up to the size of the array minus 1 is generated. The seq 0 $(( ${#ARRAYEX[@]} - 1 )) part expands to:

0 1 2 3 4

assuming that the ARRAYEX has a size of 5.

Inside the loop the array is used again, so the loop is iterating over all array element (as the first element of the array starts at 0).

Upvotes: 9

choroba
choroba

Reputation: 242103

seq 0 $(( ${#ARRAYEX[@]} - 1 )) creates a sequence of all the possible indexes of the array. You can also use

for ((i=0; i<${#ARRAYEX[@]}; ++i )) ; do

Upvotes: 2

Related Questions