使用动态变量进行数组复制

使用动态变量进行数组复制

我有一个包含 24 个元素的数组,存储在数组下MBA_分机

echo ${mba_ext[13]} gives me expected results.

现在我已经创建了一个变量temp="mba_ext"

现在我试图通过使用临时变量将数组的内容复制到另一个数组。我写的代码如下所示:

new_array=$(eval echo '$'{${temp}[@]})

当我给出时,echo$new_array我得到打印的数组的所有内容,没有任何索引。

当我付出时,echo ${new_array[4]}我没有得到任何结果。理想情况下,此命令应打印索引位置 4 处的内容。

有人可以帮忙吗?

答案1

基于这个答案在超级用户上

您可以将变量间接与适当的数组一起使用[...]。棘手的是,您必须将数组元素(或[@]所有元素)包含在您间接通过的变量中。

包含您使用的名称的示例代码:

mba_ext=('normal' 'with space' 'double"quote' "single'quote" $'new-\n-line' '\backslash')
temp="mba_ext"
temparray="${temp}[@]"   # This includes the array name AND "[@]"
new_array=("${!temparray}")
printf '<%s>\n' "${new_array[@]}"

相关内容