如何使用一系列交替的键和值来定义Bash 5.1关联数组? [英] How can I use as a sequence of alternating keys and values to define a Bash 5.1 associative array?

查看:316
本文介绍了如何使用一系列交替的键和值来定义Bash 5.1关联数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我阅读了 Bash 5.1的发行说明:

gg.可以使用复合分配中的键值对列表来分配关联数组.单词不是[key] = value形式的复合分配被认为是键-值分配.缺少键或空键是错误;缺少的值将被视为NULL.作业不能将两种形式混在一起.

gg. Associative arrays may be assigned using a list of key-value pairs within a compound assignment. Compound assignments where the words are not of the form [key]=value are assumed to be key-value assignments. A missing or empty key is an error; a missing value is treated as NULL. Assignments may not mix the two forms.

检查 Bash 5.1参考手册→数组部分我看到了这个新块(与

Checking on the Bash 5.1 Reference Manual → Arrays section I see this new block (comparing to the Bash 4.4 Reference Manual):

当分配给关联数组时,复合赋值中的单词可以是需要下标的赋值语句,也可以是被解释为交替键和值的序列的单词列表: name=(key1 value1 key2 value2…).这些名称与 name =([key1] = value1 [key2] = value2…)相同.列表中的第一个单词确定其余单词的解释方式;列表中的所有分配必须为同一类型.使用键/值对时,键可能不会丢失或为空;最后的缺失值被视为空字符串.

When assigning to an associative array, the words in a compound assignment may be either assignment statements, for which the subscript is required, or a list of words that is interpreted as a sequence of alternating keys and values: name=(key1 value1 key2 value2 … ). These are treated identically to name=( [key1]=value1 [key2]=value2 … ). The first word in the list determines how the remaining words are interpreted; all assignments in a list must be of the same type. When using key/value pairs, the keys may not be missing or empty; a final missing value is treated like the empty string.

内置的声明也接受此语法.可以使用上面介绍的 name [subscript] = value 语法将各个数组元素分配给它们.

This syntax is also accepted by the declare builtin. Individual array elements may be assigned to using the name[subscript]=value syntax introduced above.

所以我做了一个测试:

$ bash --version
GNU bash, version 5.1.0(1)-release (x86_64-apple-darwin18.5.0)
$ declare -a bla
$ bla=( [name]=me )
$ echo "${bla[name]}"
me      # it works well

但是,如果我使用新的语法,那么它对我不起作用,它将返回键而不是值:

However, if I use the new syntax it does not work to me and it returns me the key instead of the value:

$ declare -a bla
$ ble=( name me )
$ echo "${ble[name]}"
name      # should be "me"

如何正确地将复合赋值用作键和值的交替序列?

How can I properly use the compound assignment as a sequence of alternating keys and values?

推荐答案

declare -A (请注意"A"的大写字母)定义关联数组是一个问题:/p>

It is a matter of defining the associative array with declare -A (note the capital letter for "A"):

declare -A bla
$ bla=(k1 v1 k2 v2)
$ echo "${bla[k1]}"
v1

如果您尝试混合分配,则指示失败:

If you try to mix assignations, it fails as indicated:

$ bla=([k1]=v1 k2 v2)
bash: bla: k2: must use subscript when assigning associative array
bash: bla: v2: must use subscript when assigning associative array
$ bla=([k1]=v1 [k2]=v2)
$ echo "${bla[k2]}"
v2

这篇关于如何使用一系列交替的键和值来定义Bash 5.1关联数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆