Easiest way to check for an index or a key in an array?

后端 未结 7 1719
小鲜肉
小鲜肉 2020-12-02 07:30

Using:

set -o nounset
  1. Having an indexed array like:

    myArray=( "red" "black" "blue" )
             
    
    
            
7条回答
  •  一向
    一向 (楼主)
    2020-12-02 07:42

    From man bash, conditional expressions:

    -v varname
                  True if the shell variable varname is set (has been assigned a value).
    

    example:

    declare -A foo
    foo[bar]="this is bar"
    foo[baz]=""
    if [[ -v "foo[bar]" ]] ; then
      echo "foo[bar] is set"
    fi
    if [[ -v "foo[baz]" ]] ; then
      echo "foo[baz] is set"
    fi
    if [[ -v "foo[quux]" ]] ; then
      echo "foo[quux] is set"
    fi
    

    This will show that both foo[bar] and foo[baz] are set (even though the latter is set to an empty value) and foo[quux] is not.

提交回复
热议问题