使用bash关联数组预期的语法错误操作数

时间:2017-05-13 00:26:13

标签: arrays bash associative-array

我有一个关联数组的点文件名到ids,看起来完全像这样:

declare -A ids=(
  [".steve"]="1 4 5 6 10"
  [".john"]="3 4 5 1 11"
  ...
)

当我运行此代码时,我得到:

./declare_ids.sh: line 23: .steve: operand expected (error token is ".steve")

这个错误看起来真的很模糊。我不明白发生了什么。我是bash的新手,刚刚学习了bash v4中的关联数组。有人可以帮忙吗?

修改

此脚本中的shebang行是#!/bin/bash。我在OS X的zsh终端内运行,我通过brew install bash安装了bash。

bash --version说:

GNU bash, version 4.4.12(1)-release (x86_64-apple-darwin15.6.0)                                                                                                │
Copyright (C) 2016 Free Software Foundation, Inc.                                                                                                              │
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>                                                                                  │
                                                                                                                                                               │
This is free software; you are free to change and redistribute it.                                                                                             │
There is NO WARRANTY, to the extent permitted by law.

当我将bash --version放在declare -A行之前时也是如此。

which bash返回/usr/local/bin/bash。只需键入./declare_ids.sh即可在终端内调用该脚本。

再次编辑:

正如已经说过,回复$BASH_VERSIONbash --version不同。 $BASH_VERSION是3.2.57(1) - 发布。

有没有办法让/ bin / bash升级?我也在ubuntu circleCI盒子上使用这个脚本,所以任何硬编码到brew的内容都会很糟糕。

1 个答案:

答案 0 :(得分:1)

最可能的解释是,您的bash版本太旧而无法实现关联数组,例如,如果您使用的是OS X中的默认版本,则可能就是这种情况。

通过放置命令获取正在运行的bash的最终版本:

echo $BASH_VERSION

declare -A之前。 (您也可以使用命令/path/to/bash --version,其中/path/to/bash是shebang行的完整路径;在这种情况下/bin/bash

错误消息确实不容易解释,但是旧版本需要时间旅行才能告诉您使用的语法尚未添加到shell中。该错误来自declare内置将带括号的参数解释为索引数组,即使没有var=(选项,它也会在看到-a时自动执行。在索引数组中,下标必须是数字(整数,以bash术语表示),而[.steve]不是数字。 (引号无关紧要; ["3"]可以正常工作,因为bash允许您引用数字表达式中的数字。奇怪的是,[steve]也可以正常工作,因为在数值表达式中,变量名称不是已定义的变量被视为0。)

相关问题