如何在bash中检查字典是否包含键?

如何在bash中检查字典是否包含键?,bash,dictionary,Bash,Dictionary,我想查一下字典里是否有键,但我不知道怎么查。 我试过这个: if [ -z "${codeDict["$STR_ARRAY[2]"]+xxx}" ] then echo "codeDict not contains ${STR_ARRAY[2]}" codeDict["${STR_ARRAY[2]}"]="${STR_ARRAY[3]}" fi 您的方法没有问题(使用-z),如本例所示: $ declare -A a $ a=( [a]=1 [b]=2 [d]=4 ) $ [[

我想查一下字典里是否有键,但我不知道怎么查。 我试过这个:

if [ -z "${codeDict["$STR_ARRAY[2]"]+xxx}" ]
then
    echo "codeDict not contains ${STR_ARRAY[2]}"
    codeDict["${STR_ARRAY[2]}"]="${STR_ARRAY[3]}"
fi

您的方法没有问题(使用
-z
),如本例所示:

$ declare -A a
$ a=( [a]=1 [b]=2 [d]=4 )
$ [[ -z ${a[a]} ]] && echo unset
$ [[ -z ${a[c]} ]] && echo unset
unset
然而,在您的问题中,代码有几个问题。您缺少了内部数组周围的花括号,我个人建议您使用扩展测试(
[
而不是
[
),以避免混淆引号:

$ str=( a b c )
$ [[ -z ${a[${str[0]}]} ]] && echo unset
$ [[ -z ${a[${str[2]}]} ]] && echo unset
unset

如果您使用的是
bash
4.3,则可以使用
-v
测试:

if [[ -v codeDict["${STR_ARRAY[2]}"] ]]; then
    # codeDict has ${STR_ARRAY[2]} as a key
else
    # codeDict does not have ${STR_ARRAY[2]} as a key
fi
否则,您需要注意区分映射到空字符串的键和根本不在数组中的键

key=${STR_ARRARY[2]}
tmp=codeDict["$key"]  # Save a lot of typing
# ${!tmp} expands to the actual value (which may be the empty string),
#         or the empty string if the key does not exist
# ${!tmp-foo} expands to the actual value (which may be the empty string),
#             or "foo" if the key does not exist
# ${!tmp:-foo} expands to the actual value if it is a non-empty string,
#              or "foo" if the key does not exist *or* the key maps
#              to the empty string.
if [[ ${!tmp} = ${!tmp-foo} || ${!tmp} = ${!tmp:-foo} ]]; then
    # $key is a key
else
    # $key is not a key
fi
在支持关联数组的任何版本的
bash
中,如果只想为不存在的键提供默认值,则可以使用简单的单行程序

: ${codeDict["${STR_ARRAY[2]}"]="${STR_ARRAY[3]}"}

您在测试中错过了
STR_数组
扩展中的
{}
。噢……非常感谢!它无法区分缺少的条目和值为空字符串的条目。