如何检查我的Bash脚本中是否存在关联数组元素?

sen*_*rio 10 bash

我有一系列动物:

declare -A animals=()
animals+=([horse])
Run Code Online (Sandbox Code Playgroud)

我想检查动物是否存在:

if [ -z "$animals[horse]"]; then
    echo "horse exists";
fi
Run Code Online (Sandbox Code Playgroud)

但这不起作用.

che*_*ner 15

bash4.3中,-v运算符可以应用于数组.

declare -A animals
animals[horse]=neigh
# Fish are silent
animals[fish]=
[[ -v animals[horse] ]] && echo "horse exists"
[[ -v animals[fish] ]] && echo "fish exists"
[[ -v animals[unicorn] ]] && echo "unicorn does not exist" 
Run Code Online (Sandbox Code Playgroud)

在以前的版本中,您需要更加小心地区分不存在的键和引用任何空字符串的键.

animal_exists () {
    # If the given key maps to a non-empty string (-n), the
    # key obviously exists. Otherwise, we need to check if
    # the special expansion produces an empty string or an
    # arbitrary non-empty string.
    [[ -n ${animals[$1]} || -z ${animals[$1]-foo} ]]
}

animal_exists horse && echo "horse exists"
animal_exists fish && echo "fish exists"
animal_exists unicorn || echo "unicorn does not exist"
Run Code Online (Sandbox Code Playgroud)


Dmi*_*rov 10

您的脚本中有几个拼写错误

当我按原样运行它时,我从BASH获得以下错误消息:

1. animals: [horse]: must use subscript when assigning associative array
2. [: missing `]'
Run Code Online (Sandbox Code Playgroud)

第一个说如果你想horse用作关联数组的索引,你必须为它赋值.空值(null)是可以的.

-animals+=([horse])
+animals+=([horse]=)
Run Code Online (Sandbox Code Playgroud)

第二条消息说您需要将要测试的值和括号分开,因为方括号被视为值的一部分(如果没有用空格分隔)

-if [ -z "$animals[horse]"]; then
+if [ -z "$animals[horse]" ]; then
Run Code Online (Sandbox Code Playgroud)

最后,当为其分配值时,存在关联数组中的元素(即使此值为null).由于测试是否设置了数组值的问题已在本网站上得到解答,我们可以借用该解决方案

-if [ -z "$animals[horse]"]; then
+if [ -n "${animals[horse]+1}" ]; then
Run Code Online (Sandbox Code Playgroud)

为了您的方便,这里是完整的脚本:

declare -A animals=()
animals+=([horse]=)

if [ -n "${animals[horse] + 1}" ]; then
    echo "horse exists";
fi
Run Code Online (Sandbox Code Playgroud)

  • 写"animals [horse] =`比使用`+ =`要简单得多 (4认同)

anu*_*ava 3

在 BASH 中你可以这样做:

declare -A animals=()
animals+=([horse]=)

[[ "${animals[horse]+foobar}" ]] && echo "horse exists"
Run Code Online (Sandbox Code Playgroud)

"${animals[horse]+foobar}"foobar如果horse是数组中的有效索引,则返回,否则不返回任何内容。