linux - 如何转义关联数组中带有连字符的键

标签 linux bash dictionary

我想在 bash 中创建一个映射,其中一些映射键的值可能包含连字符 (-)

我试过下面的代码

declare -a buckets
buckets["us-east-1"]="bucketname-us-east-1";

region="us-east-1"
buckets[$region]="bucketname-us-east-1"; 

# both of them throws buckets["us-east-2"]: bad array subscript

buckets["us\-east\-1"]="bucketname-us-east-1"; 
# throws syntax error: invalid arithmetic operator (error token is "\-east\-1")

还有其他创建 map 的方法吗?

最佳答案

正如 Wumpus 在评论中所述,问题是您声明了一个常规的、数字索引的 array ,当您显然想要一个关联数组时。在数字索引数组的上下文中,索引为 arithmetic expressions ,这可能会导致令人困惑的错误,或者在您预期会出现错误时却没有出现错误!

$ declare -a foo
$ foo[abc-def]=bar

这是合法的,但不会将“bar”分配给索引“abc-def”。它将“bar”分配给索引 0,这是 abcdefabc-def 都扩展到的索引,因为它们没有分配.换句话说,您是从 0 中减去 0。

$ echo "${foo[0]}"
bar

如果您尝试转义破折号,则会出现错误,就像您看到的那样。

$ echo $(( abc \- def ))
bash: abc \- def : syntax error: invalid arithmetic operator (error token is "\- def ")

但是您可以在这里使用关联数组:

$ declare -A bar
$ bar[abc-def]=xyzzy
$ echo "${bar[abc-def]}"
xyzzy

这允许您在数组索引中使用字符串,并且它们不会解析为算术表达式。

编辑:错误的数组下标

一开始我没有看到错误的数组下标,因为你只能在第一次赋值给数组时得到它。

$ unset foo
$ foo[-1]=bad
bash: foo[-1]: bad array subscript

$ foo[0]=whatevz
$ foo[-1]=bad
$ # no error!

关于linux - 如何转义关联数组中带有连字符的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55710267/

相关文章:

bash - 在带有函数的 bash 中使用 set -e/set +e

arrays - Bash:如何计算数组中的唯一值并检索具有最多重复项的值

git:一个快速命令去工作树的根

python - 在 Python 中通过自定义对象值访问字典值?

c++ - 映射继承

python - 在 Python 中使用多线程迭代字典

linux - Iptables,从 prerouting Captive Portal 中排除单个 ip

linux - 删除方括号外的所有数据

javascript - 在 Linux CLI 中解释和执行任意 Javascript

c - 为什么 sigwait() 是 MT 安全的而 sigsuspend() 不是?