0

Considering an array,has say 5 elements

"${#my_array[@]}"

As this gives the array size of 5. How to get less then 1 (i.e. array_size-1)

 "${#my_array[@]}-1"

  #and

 "${#my_array[@]-1}"

doesn't work

1

1 Answer 1

4

If what you are trying to do is reference the array from the end, use negative indexes.

$: my_array=( a b c d e )
$: echo "${#my_array[@]}"
5
$: echo "${my_array[-1]}"
e
$: echo "${my_array[-2]}"
d

If you just need the numeric reference of the last element, please carefully read the links provided, but here's an example.

$: lastIndex=$(( ${#my_array[@]} - 1 ))
$: echo $lastIndex
4
$: echo ${my_array[$lastIndex]}
e

or without the $,

$: echo ${my_array[lastIndex]} # arithmetic context recognizes varnames
e
Sign up to request clarification or add additional context in comments.

2 Comments

Note that the index of an numerically indexed array is an arithmetic expression, so you can do this: ${my_array[ ${#my_array[@]} - 2 ]}, but the negative indices are much more readable.
Also, because the index is an arithmetic expression, you can omit the $: ${my_array[lastIndex]}

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.