如果您的Bash足够新,请使用-n间接变量属性,如下所示:#!/usr/bin/env bash
source values.sh
read -r -p 'Enter Identifier : ' pk
declare -n \
value1="${pk}_value1" \
value2="${pk}_value2" \
value3="${pk}_value3"
从文件values.sh填充关联数组的替代方法:#!/usr/bin/env bash
declare -A values="($(
xargs -l1 \
bash -c \
'IFS="=" read -r k v <<
))"
read -r -p 'Enter Identifier : ' pk
declare -- \
value1="${values[${pk}_value1]}" \
value2="${values[${pk}_value2]}" \
value3="${values[${pk}_value3]}"
关联数组总体的工作:
[xargs -l1会将stdio输入流的行(在这里:
xargs调用的命令是bash -c,女巫执行一个内联脚本,在这里详细介绍:# Read variables k and v from the arguments
# streamed as a here-string <<
# using the = sign as the Internal Field Separator.
# Actually splitting key=value into k and v.
IFS="=" read -r k v <<
# Format variables k and v into an Associative array
# entry declaration in the form [key]=value,
# with %q adding quotes or escaping if required.
printf "[%q]=%q\n" "$k" "$v"
最后,关联数组声明和赋值declare -A values="($(commands))"获取由xarg和嵌入式外壳程序脚本commands生成的条目。