猫test.sh
#!/bin/bash
key="index";
arr[$key]="val"
echo ${arr[${key}]}
/ bin / bash-x test.sh
+ key=index
+ arr[$key]=val
+ echo val
val
然后我修改test.sh:
#!/bin/bash
key="index.index";
arr[$key]="val"
echo ${arr[${key}]}
/ bin / bash -x test.sh
+ key=index.index
+ arr[$key]=val
test.sh: line 3: index.index: Syntax error: invalid arithmetic operator (error token is ".index")
test.sh: line 4: index.index: Syntax error: invalid arithmetic operator (error token is ".index")
为什么会出现此错误,任何建议都会受到欢迎!
最佳答案
使用declare -A arr将数组变量声明为关联数组.
原文链接:https://www.f2er.com/linux/440248.html$cat test.sh
#!/bin/bash
set -x
declare -A arr
key="index.index";
arr["$key"]="val"
echo "${arr["${key}"]}"
$./test.sh
+ declare -A arr
+ key=index.index
+ arr["$key"]=val
+ echo val
val