Bash arrays and negative subscripts, yes or no?

后端 未结 5 1972
感动是毒
感动是毒 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:41

    According to Greg Wooledge's wiki, (which links to the bash changelog) the negative index syntax was added to bash in version 4.2 alpha.

    0 讨论(0)
  • 2021-02-08 00:45

    The negative subscript works perfectly fine for me on my computer with Ubuntu 14.04 / GNU bash version 4.3.11(1) however it returns:

    line 46: [-1]: bad array subscript
    

    When I try to run the same script on 4.2.46(1). I

    0 讨论(0)
  • 2021-02-08 00:51

    If you just want the last element

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

    If you want next to last element

    $ echo ${muh[*]: -2:1}
    bleh
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-02-08 00:56

    If you do man bash the section on arrays does not list this behavior. It might be something new (gnu?) in bash.

    Fails for me in CentOS 6.3 (bash 4.1.2)

    0 讨论(0)
提交回复
热议问题