Bash – how to count the length of an array defined in bash

arraybash

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
done

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

1/3
2/3
3/3

Thanks for any kind of tips.

Best Answer

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
Related Question