Bash arrays and negative subscripts, yes or no?

后端 未结 5 1974
感动是毒
感动是毒 2021-02-08 00:32

The GNU bash manual tells me

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

name[subscript]=v         


        
5条回答
  •  情话喂你
    2021-02-08 00:55

    Old bashes (like the default one on Macs these days) don't support negative subscripts. Apart from the "substring expansion" used in the accepted answer, a possible workaround is to count the desired index from the array start within the brackets:

    $ array=(one two three)
    $ echo "${array[${#array[@]}-1]}"
    three
    

    With this approach, you can pack other parameter expansion operations into the term, e.g. "remove matching prefix pattern" th:

    $ echo "${array[${#array[@]}-1]#th}"
    ree
    

提交回复
热议问题