如何转义关联数组中具有连字符的键

him*_*219 3 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")
Run Code Online (Sandbox Code Playgroud)

还有其他创建地图的方法吗?

koj*_*iro 5

作为Wumpus在评论中指出,问题是,你声明的常客,数字索引的数组,当你想清楚的关联数组。在数字索引数组的上下文中,索引是算术表达式,它们可能导致混淆的错误,或者在您可能期望有错误的情况下没有错误!

$ declare -a foo
$ foo[abc-def]=bar
Run Code Online (Sandbox Code Playgroud)

这是合法的,但不会将“ bar”分配给索引“ abc-def”。它将“ bar”分配给索引0(即索引)abcdef并且abc-def由于未分配而全部扩展到索引0 。换句话说,您要从0中减去0。

$ echo "${foo[0]}"
bar
Run Code Online (Sandbox Code Playgroud)

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

$ echo $(( abc \- def ))
bash: abc \- def : syntax error: invalid arithmetic operator (error token is "\- def ")
Run Code Online (Sandbox Code Playgroud)

但是您可以在此处使用关联数组:

$ declare -A bar
$ bar[abc-def]=xyzzy
$ echo "${bar[abc-def]}"
xyzzy
Run Code Online (Sandbox Code Playgroud)

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

编辑: bad array subscript

我最初没有看到不良的数组下标,因为您只能在第一次分配给数组时得到它。

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

$ foo[0]=whatevz
$ foo[-1]=bad
$ # no error!
Run Code Online (Sandbox Code Playgroud)