How can I check if a string is in an array without iterating over the elements?
bash
Solution
With bash 4, the closest thing you can do is use associative arrays.
declare -A map
for name in hello world my name is perseus; do
map["$name"]=1
done
...which does the exact same thing as:
declare -A map=( [hello]=1 [my]=1 [name]=1 [is]=1 [perseus]=1 )
...followed by:
tgt=henry
if [[ ${map["$tgt"]} ]] ; then
: found
fi
Problem
Is there a way of checking if a string exists in an array of strings - without iterating through the array? For example, given the script below, how I can correctly implement it to test if the value stored in variable $test exists in $array? ``` array=('hello' 'world' 'my' 'name' 'is' 'perseus') #pseudo code $test='henry' if [$array[$test]] then do something else something else fi ``` Note I am using bash 4.1.5