我试图替换一个字符串变量(这里是一个数组),但是我收到了一个错误。有谁能建议如何解决这个问题?
COMP="MY"
MY_common_sections_to_fix=( \
".rodata" \
".data" \
)
echo ${${COMP}_common_sections_to_fix[@]}
ERROR:
$ {$ {COMP} _common_sections_to_fix [@]}:糟糕的替换
答案 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"