Bash手册页介绍了使用${!a}
来返回变量名称的内容,该变量的名称是内容的内容a
(间接级别)。
我想知道如何使用此方法返回数组中的所有元素,即
a=(one two three)
echo ${a[*]}
退货
one two three
我想要:
b=a
echo ${!b[*]}
返回相同的。不幸的是,它不是,而是返回0
。
更新
有了这些答复,我现在意识到我的示例太简单了,因为类似这样:
b=("${a[@]}")
完全可以实现我所说的需求。
所以,这是我正在尝试做的事情:
LIST_lys=(lys1 lys2)
LIST_diaspar=(diaspar1 diaspar2)
whichone=$1 # 'lys' or 'diaspar'
_LIST=LIST_$whichone
LIST=${!_LIST[*]}
当然,仔细阅读Bash手册页会发现这并不符合预期,因为最后一行只是返回“数组”的索引$_LIST
(根本不是数组)。
在任何情况下,都应执行以下操作(如所指出的那样):
LIST=($(eval echo \${$_LIST[*]}))
或...(最终我走的路线):
LIST_lys="lys1 lys2"
...
LIST=(${!_LIST})
当然,假设元素不包含空格。
我认为应从字面上对待使用bash变量的间接引用。
例如。对于您的原始示例:
a=(one two three)
echo ${a[*]} # one two three
b=a
echo ${!b[*]} # this would not work, because this notation
# gives the indices of the variable b which
# is a string in this case and could be thought
# as a array that conatins only one element, so
# we get 0 which means the first element
c='a[*]'
echo ${!c} # this will do exactly what you want in the first
# place
对于最后一个真实场景,我相信下面的代码可以完成工作。
LIST_lys=(lys1 lys2)
LIST_diaspar=(diaspar1 diaspar2)
whichone=$1 # 'lys' or 'diaspar'
_LIST="LIST_$whichone"[*]
LIST=( "${!_LIST}" ) # Of course for indexed array only
# and not a sparse one
最好使用"${var[@]}"
避免与$IFS
and参数扩展混淆的符号。这是最终代码。
LIST_lys=(lys1 lys2)
LIST_diaspar=(diaspar1 diaspar2)
whichone=$1 # 'lys' or 'diaspar'
_LIST="LIST_$whichone"[@]
LIST=( "${!_LIST}" ) # Of course for indexed array only
# and not a sparse one
# It is essential to have ${!_LIST} quoted
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句