linux - shell 中的 "invalid arithmetic operator"

标签 linux bash shell unix

猫测试.sh

#!/bin/bash
key="index";
arr[$key]="val"
echo ${arr[${key}]}

/bin/bash-x 测试.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")

为什么会出现这个错误,任何建议将不胜感激!

最佳答案

这个:

key="index";
arr[$key]="val"
echo ${arr[${key}]}

只有似乎 可以工作。自 arr是普通数组,不是关联数组,只能用非负整数值索引。

考虑这个有效代码:

index=42
key="index"
arr[$key]="val"
echo ${arr[42]}
echo ${arr[index]}
echo ${arr[$index]}
echo ${arr['index']}
echo ${arr["index"]}
echo ${arr[\index]}

所有 echo报表打印 val .由于索引被视为算术表达式,因此它可以引用带有或不带 $index 的变量(在本例中为 $)。前缀——即使它是一个带引号的字符串。

在您的代码中,您从未为 $index 赋值, ${arr[${key}]}扩展为 ${arr[index]} ,相当于 ${arr[$index]} , 被视为(默认情况下)等同于 ${arr[0]} .

(如果您有 set -o nounset ,那么对未设置变量的引用将被视为错误,并且您的代码将产生一条错误消息。)

你的第二段代码:

key="index.index";
arr[$key]="val"
echo ${arr[${key}]}

无效,因为 index.index不是有效的变量名——即使您可能认为它只是用作数组索引的字符串。

如果你想要arr要允许任意字符串作为索引,它需要是一个关联数组。您可以简单地通过分配给它(或使用 declare -a )来创建非关联数组,但是关联数组只能使用 declare -A 创建。 .

关联数组已添加到版本 4 中的 bash。如果您使用的是早期版本的 bash,declare -A不支持。您需要升级到更新的 bash,编写一些笨拙的替代方案,或者使用支持关联数组的语言,例如 Awk、Python 或 Perl。

添加declare -A arr (如 user000001's answer 所建议的那样)应该可以解决问题(如果您有 bash 4),但了解您的原始代码实际在做什么(或不做什么)是有指导意义的。

(顺便说一句,感谢您提出这个问题;我在撰写此答案时学到了很多东西。)

关于linux - shell 中的 "invalid arithmetic operator",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18250857/

相关文章:

php - innobackupex 流 tar 并从 php 运行

linux - unix bash 查找具有 2 个显式文件扩展名的文件目录

linux - 用于更新 Deluged Interface IP 的 Bash 脚本无法作为 cron 作业运行,但在手动运行时有效

linux - Bash脚本被杀死时如何杀死当前命令

linux - Bash 脚本 : cd No such file or directory when file exists

python - Homebrew 将 python 链接到/usr/local/bin/on Mac

ios - Appledoc 无法在 Xcode 中运行

linux - 从shell脚本中的字符串中删除单引号

java - 无法使用 Java ProcessBuilder 启动带有参数的 shell 脚本

c - execl() 查找命令 c