假设我有一些bash数组:
A1=(apple trees)
A2=(building blocks)
A3=(color television)
Run Code Online (Sandbox Code Playgroud)
和索引一样J=2,如何获取数组内容A2?
Xiè*_*léi 20
我已经找到了解决方案,这可以通过以下方式完成:
$ Aref=A$J
$ echo ${!Aref}
building
$ Aref=A$J[1]
$ echo ${!Aref}
blocks
$ Aref=A$J[@]
$ echo "${!Aref}"
building blocks
Run Code Online (Sandbox Code Playgroud)
小智 17
值得注意的是,即使是在评估变量时也会替换索引:
$ A2=(building blocks)
$ Aref=A2[index]
$ index=1
$ echo "${!Aref}"
blocks
Run Code Online (Sandbox Code Playgroud)
今天(使用 bash 4.3 及更高版本),最佳实践是使用nameref支持:
A1=(apple trees)
A2=(building blocks)
A3=(color television)
J=2
declare -n A="A$J"
printf '%q\n' "${A[@]}"
Run Code Online (Sandbox Code Playgroud)
...将正确发出:
building
blocks
Run Code Online (Sandbox Code Playgroud)
这也可nameref A="A$J"用于 ksh93。有关详细信息,请参阅BashFAQ #6。