how to count the length of an array defined in bash?

I’m new to bash and can’t find a good tutorial to answer my question.

array=( item1 item2 item3 )
for name in ${array[@]}; do
    echo current/total
    ... some other codes

I want to calculate the current and total value, as the expected output of this being:


Thanks for any kind of tips.

Asked By: AGamePlayer


You can access the array indices using ${!array[@]} and the length of the array using ${#array[@]}, e.g. :


array=( item1 item2 item3 )
for index in ${!array[@]}; do
    echo $index/${#array[@]}

Note that since bash arrays are zero indexed, you will actually get :


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.


array=( item1 item2 item3 )
for index in ${!array[@]}; do
    echo $((index+1))/${#array[@]} = "${array[index]}"


1/3 = item1
2/3 = item2
3/3 = item3
Answered By: steeldriver

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)); 
if n > m then 

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].

Answered By: Donald Darden
Categories: Answers Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.