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

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

Using:

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

    myArray=( "red" "black" "blue" )
             
    
    
            
7条回答
  •  甜味超标
    2020-12-02 07:47

    tested in bash 4.3.39(1)-release

    declare -A fmap
    fmap['foo']="boo"
    
    key='foo'
    # should echo foo is set to 'boo'
    if [[ -z "${fmap[${key}]}" ]]; then echo "$key is unset in fmap"; else echo "${key} is set to '${fmap[${key}]}'"; fi
    key='blah'
    # should echo blah is unset in fmap
    if [[ -z "${fmap[${key}]}" ]]; then echo "$key is unset in fmap"; else echo "${key} is set to '${fmap[${key}]}'"; fi
    

提交回复
热议问题