我想检查字典是否包含键,但我不知道如何。我试过这个:
if [ -z "${codeDict["$STR_ARRAY[2]"]+xxx}" ]
then
echo "codeDict not contains ${STR_ARRAY[2]}"
codeDict["${STR_ARRAY[2]}"]="${STR_ARRAY[3]}"
fi
Run Code Online (Sandbox Code Playgroud)
您的方法(使用-z)没有任何问题,如本示例所示:
$ declare -A a
$ a=( [a]=1 [b]=2 [d]=4 )
$ [[ -z ${a[a]} ]] && echo unset
$ [[ -z ${a[c]} ]] && echo unset
unset
Run Code Online (Sandbox Code Playgroud)
但是,您的问题中的代码存在一些问题。您缺少内部数组周围的花括号,我个人建议您使用扩展测试([[而不是[)以避免混淆引号:
$ str=( a b c )
$ [[ -z ${a[${str[0]}]} ]] && echo unset
$ [[ -z ${a[${str[2]}]} ]] && echo unset
unset
Run Code Online (Sandbox Code Playgroud)
如果你使用的是bash4.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
Run Code Online (Sandbox Code Playgroud)
否则,您需要注意区分映射到空字符串的键和根本不在数组中的键。
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
Run Code Online (Sandbox Code Playgroud)
在任何bash支持关联数组的版本中,如果您只想为不存在的键提供默认值,则可以使用简单的单行。
: ${codeDict["${STR_ARRAY[2]}"]="${STR_ARRAY[3]}"}
Run Code Online (Sandbox Code Playgroud)