bob.sacamento bob.sacamento - 1 year ago 92
Linux Question

Bash arrays and negative subscripts, yes or no?

The GNU bash manual tells me

An indexed array is created automatically if any variable is assigned
to using the syntax


The subscript is treated as an arithmetic expression that must
evaluate to a number. If subscript evaluates to a number less than
zero, it is used as an offset from one greater than the array’s
maximum index (so a subcript of -1 refers to the last element of the

So I figure I will give it a try and get the following result:

$ muh=(1 4 'a' 'bleh' 2)
$ echo $muh
$ echo ${muh[*]}
1 4 a bleh 2 # so far so good so now I'll try a negative ...
$ echo ${muh[-1]}
-bash: muh: bad array subscript # didn't go as planned!

Did I do something wrong, or is the website wrong, or is gnu bash that different from the bash I am running under CentOS? Thanks!

Answer Source

If you just want the last element

$ echo ${muh[*]: -1}

If you want next to last element

$ echo ${muh[*]: -2:1}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download