Bash indirect array addressing?

后端 未结 3 2113
离开以前
离开以前 2020-11-28 09:55

Suppose I have some bash arrays:

A1=(apple trees)
A2=(building blocks)
A3=(color television)

And index J=2, how

相关标签:
3条回答
  • 2020-11-28 10:23

    Today (with bash 4.3 and later), the best practice is to use nameref support:

    A1=(apple trees)
    A2=(building blocks)
    A3=(color television)
    J=2
    
    declare -n A="A$J"
    printf '%q\n' "${A[@]}"
    

    ...will properly emit:

    building
    blocks
    

    This is also available as nameref A="A$J" on ksh93. See BashFAQ #6 for details.

    0 讨论(0)
  • 2020-11-28 10:27

    It’s worth to note, that even an index will be substituted at time the variable is evaluated:

    $ A2=(building blocks)
    $ Aref=A2[index]
    $ index=1
    $ echo "${!Aref}"
    blocks
    
    0 讨论(0)
  • 2020-11-28 10:42

    I've already found a resolution, this can be done by:

    $ Aref=A$J
    $ echo ${!Aref}
    building
    $ Aref=A$J[1]
    $ echo ${!Aref}
    blocks
    $ Aref=A$J[@]
    $ echo "${!Aref}"
    building blocks
    
    0 讨论(0)
提交回复
热议问题