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

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

Using:

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

    myArray=( "red" "black" "blue" )
             
    
    
            
7条回答
  •  旧巷少年郎
    2020-12-02 07:39

    This is the easiest way I found for scripts.

    is the string you want to find, ASSOC_ARRAY the name of the variable holding your associative array.

    Dependign on what you want to achieve:

    key exists:

    if grep -qe "" <(echo "${!ASSOC_ARRAY[@]}"); then echo key is present; fi
    

    key exists not:

    if ! grep -qe "" <(echo "${!ASSOC_ARRAY[@]}"); then echo key not present; fi
    

    value exists:

    if grep -qe "" <(echo "${ASSOC_ARRAY[@]}"); then echo value is present; fi
    

    value exists not:

    if ! grep -qe "" <(echo "${ASSOC_ARRAY[@]}"); then echo value not present; fi
    

提交回复
热议问题