采用可变间接扩张猛砸阵列扩展 [英] Bash array expansion using variable indirection expansion
问题描述
我试图扩大数组通过间接扩展我得到的所有值:
I am trying to expand all values in an array I get to through indirect expansion:
> my_array=(coconut banana)
> echo "${my_array[@]}"
coconut banana
> my_array_name=my_array
> echo ${!my_array_name}
coconut
> echo "${!my_array_name[@]}"
0
我错误地使用数组键的列表中的最后一个命令,因为我不知道如何键入正确的命令?
I am erroneously using "List of array keys" in the last command because I don't know how to type the right command?
我想获得:
coconut banana
可能不诉诸有些难看评估
黑客..实例一吸黑客:
possibly without resorting to some ugly eval
hack.. Example of one suck hack:
> echo \${$my_array_name[@]}
${my_array[@]}
> eval echo \${$my_array_name[@]}
coconut banana
注意
my_array
可能包含空格的值!
在我写的功能,my_array_name是通过$ 1设置,所以我不能使用,从字面上。
In the function I am writing, my_array_name is set through "$1" so I cannot use that literally.
类似于:<一href=\"http://unix.stackexchange.com/questions/20171/indirect-return-of-all-elements-in-an-array\">http://unix.stackexchange.com/questions/20171/indirect-return-of-all-elements-in-an-array但我需要避免使用评估
从讨厌的影响,如果环境被黑客的剧本将有保障的只是在正确的时间的。 ..
Similar to: http://unix.stackexchange.com/questions/20171/indirect-return-of-all-elements-in-an-array but I need to avoid using eval
to protect from the nasty effects the script would have if the environment was "hacked" just at the right time...
推荐答案
这应该工作
my_array_name='my_array[@]'
echo "${!my_array_name}"
评论后:你要创建阵列和名称的字符串[@]',另一个例子
After comment : you have to create a string with the name of the array and '[@]', another example
my_array_name="$1"'[@]'
echo "${!my_array_name}"
注释之后:测试在一个函数
After comment : test in a function
display_elem() {
local arrname
arrname="$1[@]"
printf "%s\n" "${!arrname}"
}
display_elem my_array
这篇关于采用可变间接扩张猛砸阵列扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!