Test if element is in array in bash
In Bash 4, you can use associative arrays:
# set up array of constants
declare -A array
for constant in foo bar baz
do
array[$constant]=1
done
# test for existence
test1="bar"
test2="xyzzy"
if [[ ${array[$test1]} ]]; then echo "Exists"; fi # Exists
if [[ ${array[$test2]} ]]; then echo "Exists"; fi # doesn't
To set up the array initially you could also do direct assignments:
array[foo]=1
array[bar]=1
# etc.
or this way:
array=([foo]=1 [bar]=1 [baz]=1)
It's an old question, but I think what is the simplest solution has not appeared yet: test ${array[key]+_}
. Example:
declare -A xs=([a]=1 [b]="")
test ${xs[a]+_} && echo "a is set"
test ${xs[b]+_} && echo "b is set"
test ${xs[c]+_} && echo "c is set"
Outputs:
a is set
b is set
To see how this work check this.
There is a way to test if an element of an associative array exists (not set), this is different from empty:
isNotSet() {
if [[ ! ${!1} && ${!1-_} ]]
then
return 1
fi
}
Then use it:
declare -A assoc
KEY="key"
isNotSet assoc[${KEY}]
if [ $? -ne 0 ]
then
echo "${KEY} is not set."
fi