Using:
set -o nounset
Having an indexed array like:
myArray=( "red" "black" "blue" )
>
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
array[key] is set, return abcarray[key] is not set, return nothingSee Parameter Expansion in Bash manual and the little note
if the colon is omitted, the operator tests only for existence [of parameter]
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