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

Luca Borrione picture Luca Borrione · Nov 4, 2012 · Viewed 79.2k times · Source

Using:

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

    myArray=( "red" "black" "blue" )
    

    What is the shortest way to check if element 1 is set?
    I sometimes use the following:

    test "${#myArray[@]}" -gt "1" && echo "1 exists" || echo "1 doesn't exist"
    

    I would like to know if there's a preferred one.

  2. How to deal with non-consecutive indexes?

    myArray=()
    myArray[12]="red"
    myArray[51]="black"
    myArray[129]="blue"
    

    How to quick check that 51 is already set for example?

  3. How to deal with associative arrays?

    declare -A myArray
    myArray["key1"]="red"
    myArray["key2"]="black"
    myArray["key3"]="blue"
    

    How to quick check that key2 is already used for example?

Answer

doubleDown picture doubleDown · Nov 4, 2012

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