51

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

  • Note that you should put ${array[@]} in double quotes. Otherwise, word-splitting will be performed and you will get undesirable results, on inputs like array=("item 1" "item 2" "item 3"). – gardenhead Jan 10 '16 at 7:57
90

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
  • If I want to get 1,2,3, can I do this: echo ($index+1)/${#array[@]}? – AGamePlayer Mar 28 '15 at 3:05
  • btw, it seems that in this way I can't get item1, item2, item3 in the loop. I still have other code to deal with the item1, item2, item3 stuff. Thanks, – AGamePlayer Mar 28 '15 at 3:06
  • See edited post. – steeldriver Mar 28 '15 at 3:14
2

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.