猫test.sh
#!/bin/bash
key="index";
arr[$key]="val"
echo ${arr[${key}]}
@H_404_7@
/ bin / bash-x test.sh
+ key=index
+ arr[$key]=val
+ echo val
val
@H_404_7@
然后我修改test.sh:
#!/bin/bash
key="index.index";
arr[$key]="val"
echo ${arr[${key}]}
@H_404_7@
/ 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")
@H_404_7@
为什么会出现此错误,任何建议都会受到欢迎!
最佳答案
使用declare -A arr将数组变量声明为关联数组.
$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
@H_404_7@