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

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]

  1. 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 

Leave a Comment