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

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

Using:

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

    myArray=( "red" "black" "blue" )
             
    
    
            
7条回答
  •  执笔经年
    2020-12-02 07:54

    What about a -z test and the :- operator?

    For example, this script:

    #!/usr/bin/env bash
    
    set -e
    set -u
    
    declare -A sample
    
    sample["ABC"]=2
    sample["DEF"]=3
    
    if [[ ! -z "${sample['ABC']:-}" ]]; then
      echo "ABC is set"
    fi
    
    if [[ ! -z "${sample['DEF']:-}" ]]; then
      echo "DEF is set"
    fi
    
    if [[ ! -z "${sample['GHI']:-}" ]]; then
      echo "GHI is set"
    fi
    

    Prints:

    ABC is set
    DEF is set
    

提交回复
热议问题