how to count the length of an array defined in bash?
You can access the array indices using ${!array[@]}
and the length of the array using ${#array[@]}
, e.g. :
#!/bin/bash
array=( item1 item2 item3 )
for index in ${!array[@]}; do
echo $index/${#array[@]}
done
Note that since bash arrays are zero indexed, you will actually get :
0/3
1/3
2/3
If you want the count to run from 1 you can replace $index
by $((index+1))
. If you want the values as well as the indices you can use "${array[index]}"
i.e.
#!/bin/bash
array=( item1 item2 item3 )
for index in ${!array[@]}; do
echo $((index+1))/${#array[@]} = "${array[index]}"
done
giving
1/3 = item1
2/3 = item2
3/3 = item3
A zero index is perfectly valid if you think of the index as actually being an offset from the base address of an array. That's the norm in fact, though it varies from dialect to dialect. With the old Jovial language, [0]
actually contained the maximum size of the array. so it started with [1]
.
With some Basic implementations, you can arbitrarily elect to have either 0
or 1
as the first index. And at least one Basic allows you to designate arrays to index fron [n]
to [m]
. where n
and m
can have any integer value, even negative, as long as n
is less than or equal to m
. The value n
them becomes subtracted from the [index]
entered, as index-n = 0
if index corresponds to n
.
But you can do the same thing and more in your own code. You can even reverse the order of an array this way:
dim array(0, abs(m-n));
step=sign(m-n);
if n > m then
base=m
else
base=n;
fi
This code example is actually only partly of one language. I just wanted it to be more readable. The step variable is used to control the apparent direction you are moving in whether positive or negative, and is used to calculate the effective index when going into or coming out of the array, which is actually always positive from [0]
.