【问题标题】:Is there a way to declare associative arrays in bash using ip addresses as indices? [duplicate]有没有办法使用 ip 地址作为索引在 bash 中声明关联数组? [复制]
【发布时间】:2018-10-10 20:32:06
【问题描述】:

我正在尝试这样做:

declare -a ip_array=( [127.0.0.1]=127.1.1.1 [127.1.1.1]=127.0.0.1 )

但是 bash 抱怨它认为小数是运算符:

bash: 127.0.0.1: syntax error: invalid arithmetic operator (error token is "127.0.0.1")

我尝试使用单引号和双引号,但它似乎每次都进行算术计算。

编辑:在声明数组时,我没有注意到小写 -a 和大写 -A 选项之间存在差异。

【问题讨论】:

  • 你需要一个关联数组:使用declare -A ... -- 带有“declare -a”的“普通”数组是数字索引的。
  • @glennjackman:您应该将其发布为答案。

标签: arrays bash


【解决方案1】:

[- +] a 将 NAMEs 声明为索引数组(使用 + 可接受的语法删除,但会导致错误消息)

[- +] A 将 NAME 声明为关联数组

试试这个:

declare -A AR=( [127.0.0.1]=127.1.1.1 [127.1.1.1]=127.0.0.1 ); echo ${AR[@]};

【讨论】:

  • 不要只发布代码,解释问题所在以及如何解决它。
  • @Barmar 已修复 :-)
猜你喜欢
  • 1970-01-01
  • 2022-11-17
  • 1970-01-01
  • 2015-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多