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

后端 未结 7 1714
小鲜肉
小鲜肉 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

    To check if the element is set (applies to both indexed and associative array)

    [ ${array[key]+abc} ] && echo "exists"
    

    Basically what ${array[key]+abc} does is

    • if array[key] is set, return abc
    • if array[key] is not set, return nothing


    References:

    1. See Parameter Expansion in Bash manual and the little note

      if the colon is omitted, the operator tests only for existence [of parameter]

    2. This answer is actually adapted from the answers for this SO question: How to tell if a string is not defined in a bash shell script?


    A wrapper function:

    exists(){
      if [ "$2" != in ]; then
        echo "Incorrect usage."
        echo "Correct usage: exists {key} in {array}"
        return
      fi   
      eval '[ ${'$3'[$1]+muahaha} ]'  
    }
    

    For example

    if ! exists key in array; then echo "No such array element"; fi 
    

提交回复
热议问题