我想在bash脚本中使用手动创建的数组(假多点数组),但在使用数组的条件下,我想使用变量中的数组名。
使用bashVersion4.1.2,因此声明-n不存在。
我想我的例子会更有帮助,看看我想做什么:
declare -A test
test[ar,action]="dosomething"
test[bc,action2]="doelse"
test[bc,resolv]="dotest"
#works:
echo "this works: ${test[bc,action2]}"
#but if i want to use a variable name, bad substitution error
name="test"
echo "01 this works: ${$name[bc,action2]}"
#another test doesn't work also
echo "02 test2 : ${!name[bc,action2]}"
#final goal is to do something like this:
if [[ "${!name[bc,action2]}" == "doelse" ]]; then
echo "mission completed"
fi检查了其他的帖子,但不能让它正常工作。
也测试过这个并且可以工作但我用这种方式丢失了索引名..。我也需要那个。
all_elems_indirection="${name[@]}"
echo "works, a list of items : ${!all_elems_indirection}"
test3="${name}[$cust,buyer]"
echo "test3 works : ${!test3}"
second_elem_indirection="${name}[bc,action2]"
echo "test 3 works: ${!second_elem_indirection}"
#but when i want to loop through the indexes from the array with the linked values, it doesn't work, i lost the indexes.
for i in "${!all_elems_indirection}"; do
echo "index name: $i"
done发布于 2022-03-26 11:46:42
在eval中,请您尝试以下几种方法:
#!/bin/bash
declare -A test
test[bc,action2]="doelse"
name="test"
if [[ $(eval echo '$'{"$name"'[bc,action2]}') == "doelse" ]]; then
echo "mission completed"
fi由于eval允许执行任意代码,因此我们需要最大限度地注意代码、变量和相关文件的完全控制,并且不存在修改或注入的空间。
发布于 2022-03-26 13:31:28
只是数据而已。只是短信而已。不要局限于Bash数据结构。您可以在任何底层存储上构建抽象。
mydata_init() {
printf -v "$1" ""
}
mydata_put() {
printf -v "$1" "%s\n%s\n" "${!1}" "${*:2}"
}
mydata_get2() {
local IFS
unset IFS
while read -r a b v; do
if [[ "$a" == "$2" && "$b" == "$3" ]]; then
printf -v "$4" "%s" "$v"
return 0
fi
done <<<"${!1}"
return 1
}
mydata_init test
mydata_put test ar action dosomething
mydata_put test bc action2 doelse
mydata_put test bc resolv dotest
if mydata_get2 test bc action2 var && [[ "$var" == "doelse" ]]; then
echo "mission completed"
fi当语言的内置特性对您来说还不够时,您可以:增强语言,构建自己的抽象,或者使用另一种语言。使用Perl或Python,其中表示这样的数据结构非常简单。
https://stackoverflow.com/questions/71627004
复制相似问题