gpt4 book ai didi

arrays - 间接引用 bash 中的数组值

转载 作者:行者123 更新时间:2023-11-29 09:42:40 25 4
gpt4 key购买 nike

我正在尝试在 bash 中对数组中的值进行间接引用。

anotherArray=("foo" "faa")

foo=("bar" "baz")
faa=("test1" "test2")


for indirect in ${anotherArray[@]}
do

echo ${!indirect[0]}
echo ${!indirect[1]}

done

这是行不通的。我尝试了很多不同的方法来通过回显 $indirect 来获得 $foo 的不同值,但我只能获得第一个值、所有值、“0”或什么都没有。

最佳答案

您必须在用于间接访问的变量中写入索引:

anotherArray=("foo" "faa")
foo=("bar" "baz")
faa=("test1" "test2")

for indirect in ${anotherArray[@]}; do
all_elems_indirection="${indirect}[@]"
second_elem_indirection="${indirect}[1]"
echo ${!all_elems_indirection}
echo ${!second_elem_indirection}
done

如果您想遍历 anotherArray 中引用的每个数组的每个元素,请执行以下操作:

anotherArray=("foo" "faa")
foo=("bar" "baz")
faa=("test1" "test2")

for arrayName in ${anotherArray[@]}; do
all_elems_indirection="${arrayName}[@]"
for element in ${!all_elems_indirection}; do
echo $element;
done
done

或者,您可以直接将整个间接存储在您的第一个数组中:anotherArray=("foo[@]""faa[@]")

关于arrays - 间接引用 bash 中的数组值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40307250/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com