如何检查字典是否包含bash中的密钥?

时间:2015-05-20 15:23:11

标签: bash dictionary

我想检查字典是否包含密钥,但我不知道如何。 我试过这个:

INCIDENT_NUMBER ASSIGNED INCIDENTSTA   OVERLAPSTART     OVERLAPEND       DURATION
--------------- -------- ----------- -------------- -------------- --------------
INC000000128540 Helpdesk Assigned        1431348757     1431434286          85529
INC000000128540 L1       Assigned        1431434286     1432033740         599454
INC000000128540 L2       Assigned        1432033740     1432033777             37
INC000000128540 L1       Assigned        1432033777     1432033832             55
INC000000128540 L1       In Progress     1432033832     1432034915           1083
INC000000128540 L1       Pending         1432034915     1432034927             12
INC000000128540 L2       Assigned        1432034927     1432034970             43
INC000000128540 L2       Pending         1432034970     1432034980             10
INC000000128540 L1       Pending         1432034980     1432034988              8
INC000000128540 L1       In Progress     1432034988     1432205374         170386

2 个答案:

答案 0 :(得分:2)

如果您使用的是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]}"}

答案 1 :(得分:1)

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

$ declare -A a
$ a=( [a]=1 [b]=2 [d]=4 )
$ [[ -z ${a[a]} ]] && echo unset
$ [[ -z ${a[c]} ]] && echo unset
unset

但是,您的问题中的代码存在一些问题。您错过了内部阵列周围的花括号,并且我个人建议您使用扩展测试([[而不是[)以避免不得不乱用引号:< / p>

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