有没有办法在Bash
中创建一个指向关联数组中键值的指针?喜欢这个:
declare -A mapp
mapp=( ["key"]="${value}" )
for k in "${!mapp[@]}"; do
pointer="${mapp["${k}"]}" # How do I do this?
done
通常,你不需要使用指针,但我很好奇是否有办法制作一个。
在更简单的情况下(即,对于普通/字符串变量),我会像这样制作一个指针:
pointer=b
read -p "Enter something: " b
eval pointer=$${pointer}
如何为关联阵列执行此操作?这不起作用(跳过删除线代码):
declare -A mapp
mapp=( ["first"]="${a}" ["second"]="${b}" )
for k in "${!mapp[@]}"; do
v=mapp["${k}"]
read -p "Enter ${k}: " new
eval v=$${v} # Doesn't work
done
declare -A mapp
mapp=( ["first"]="${a}" ["second"]="${b}" )
for k in "${!mapp[@]}"; do
v=mapp["${k}"]
read -p "Enter ${k}: " k
eval v=$${v} # Doesn't work
done
这也不起作用(跳过删除线代码):
declare -A mapp
mapp=( ["first"]="${a}" ["second"]="${b}" )
for k in "${!mapp[@]}"; do
v=mapp
read -p "Enter ${k}: " new
eval v=$${v["${k}"]} # Doesn't work (and has terrible readability)
done
declare -A mapp
mapp=( ["first"]="${a}" ["second"]="${b}" )
for k in "${!mapp[@]}"; do
v=mapp
read -p "Enter ${k}: " k
eval v=$${v["${k}"]} # Doesn't work (and has terrible readability)
done
在 bash
4.3 中,您可以使用 nameref:
$ mapp=([key]=value)
$ declare -n x=mapp[key] # NO dollar sign!
$ x=7
$ echo ${mapp[key]}
7
在 4.3 之前,您需要以不同的方式使用 declare
命令来执行间接寻址。
$ mapp=([key]=value)
$ x=mapp[key] # NO dollar sign!
$ declare "$x=7"
$ echo ${mapp[key]}
7
没问题:
$ declare -A ary=([foo]=bar [baz]=qux)
$ key=foo
$ pointer="ary[$key]"
$ echo "$pointer"
ary[foo]
$ echo "${!pointer}"
bar
从这个意义上说,"指针"是一个间接变量