Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if a string is in an array without iterating over the elements?

Tags:

bash

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

like image 626
Homunculus Reticulli Avatar asked Jul 09 '12 14:07

Homunculus Reticulli


People also ask

How do you check if a string is in an array?

You can use the includes() method in JavaScript to check if an item exists in an array. You can also use it to check if a substring exists within a string. It returns true if the item is found in the array/string and false if the item doesn't exist.

How do you find an array number without a loop?

You can simply use . includes() method of arrays: let a = [2, 4, 6, 8, 10], b = 2; if(a. includes(b)) { // your code goes here... }

How do you iterate through an array without knowing the size?

You cannot iterate over an array in c without knowking the number of elements. Please note that sizeof(array) / sizeof(array[0]) won't work on a pointer, i.e it will not give the number of elements in the array.


1 Answers

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
like image 85
Charles Duffy Avatar answered Sep 28 '22 01:09

Charles Duffy