将字符串变量替换为数组的名称

时间:2017-06-21 00:39:40

标签: bash

我试图替换一个字符串变量(这里是一个数组),但是我收到了一个错误。有谁能建议如何解决这个问题?

COMP="MY"

MY_common_sections_to_fix=( \
      ".rodata" \
      ".data" \
      )

 echo ${${COMP}_common_sections_to_fix[@]}

ERROR:

$ {$ {COMP} _common_sections_to_fix [@]}:糟糕的替换

1 个答案:

答案 0 :(得分:2)

您尝试做的是间接引用数组。

如果你有足够新的shell(4.3或更高版本),那么一个nameref是最合适的工具:

COMP=MY
MY_common_sections_to_fix=( .rodata .data )
declare -n active_sections=${COMP}_common_sections_to_fix
printf '%s\n' "${active_sections[@]}"

这使active_sections成为MY_common_sections_to_fix的别名,并正确地以.rodata.data作为输出。

如果您有bash 4.3可用,那么使用eval的hackery是可用的(虽然不幸)选项:

printf -v cmd '%q=( "${%q[@]}" )' active_sections "${COMP}_common_sections_to_fix"
eval "$cmd"