从名称

时间:2016-08-18 14:23:01

标签: arrays bash

在Bash中闲逛(只是为了好玩)并发现你可以引用一个数组并从变量的名称中获取它的值:

nick@nick-lt:~$ ARR=(one two);
nick@nick-lt:~$ ARRAYINDIRECT="ARR[@]"
nick@nick-lt:~$ echo "${!ARRAYINDIRECT}"
one two

我感兴趣的是,如果使用相同的方法,我们也可以获得数组的索引。通常,我会这样做:

nick@nick-lt:~$ ARR=(one two); echo "${!ARR[@]}"
0 1

但我无法找到正确的语法。以下是我尝试过的几种方式:

nick@nick-lt:~$ ARR=(one two); ARRAYINDIRECT="ARR[@]"; echo "${!!ARRAYINDIRECT}"
bash: !ARRAYINDIRECT}: event not found

ARR=(one two); ARRAYINDIRECT="!ARR[@]"; echo "${!ARRAYINDIRECT}"
bash: !ARR[@]: event not found

# Increasingly desperate attempts...
nick@nick-lt:~$ ARR=(one two); ARRAYINDIRECT="\!ARR[@]"; echo "${!ARRAYINDIRECT}"

nick@nick-lt:~$ ARR=(one two); ARRAYINDIRECT="ARR[@]"; echo "${!${!ARRAYINDIRECT}}"
bash: ${!${!ARRAYINDIRECT}}: bad substitution
nick@nick-lt:~$ ARR=(one two); ARRAYINDIRECT="ARR[@]"; echo "${\!!ARRAYINDIRECT}"
bash: !ARRAYINDIRECT}: event not found
nick@nick-lt:~$ ARR=(one two); ARRAYINDIRECT="ARR[@]"; echo "${!\!ARRAYINDIRECT}"
bash: ${!\!ARRAYINDIRECT}: bad substitution

问题:是否可以在按名称引用后获取数组的索引数组?

1 个答案:

答案 0 :(得分:2)

如果您正在使用BASH 4.2+,那么您可以使用declare -n

arr=(one two)

declare -n arrayindirect=arr

echo "${arrayindirect[@]}"
one two

echo "${!arrayindirect[@]}"
0 1

declare -p arrayindirect
declare -n arrayindirect="arr"