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

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

Using:

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

    myArray=( "red" "black" "blue" )
    
    
            
相关标签:
7条回答
  • 2020-12-02 07:59

    I wrote a function to check if a key exists in an array in Bash:

    # Check if array key exists
    # Usage: array_key_exists $array_name $key
    # Returns: 0 = key exists, 1 = key does NOT exist
    function array_key_exists() {
        local _array_name="$1"
        local _key="$2"
        local _cmd='echo ${!'$_array_name'[@]}'
        local _array_keys=($(eval $_cmd))
        local _key_exists=$(echo " ${_array_keys[@]} " | grep " $_key " &>/dev/null; echo $?)
        [[ "$_key_exists" = "0" ]] && return 0 || return 1
    }
    

    Example

    declare -A my_array
    my_array['foo']="bar"
    
    if [[ "$(array_key_exists 'my_array' 'foo'; echo $?)" = "0" ]]; then
        echo "OK"
    else
        echo "ERROR"
    fi
    

    Tested with GNU bash, version 4.1.5(1)-release (i486-pc-linux-gnu)

    0 讨论(0)
提交回复
热议问题