Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a Bash array contains a value

Tags:

arrays

bash

In Bash, what is the simplest way to test if an array contains a certain value?

like image 751
Paolo Tedesco Avatar asked Sep 10 '10 15:09

Paolo Tedesco


People also ask

How do you check if an element is present in an array in Bash?

Here is a small contribution : array=(word "two words" words) search_string="two" match=$(echo "${array[@]:0}" | grep -o $search_string) [[ ! -z $match ]] && echo "found !"

How do you check if something is in a list in Bash?

To do this, we can use the tr command. We'll echo the list and pipe it through tr DELIMITER ” “, and assign the result to a new variable. We can see, we first convert the input list so we can use the variable LIST_WHITESPACES in the for loop. Then, the function returns the value 0 if the item is found.

What does =~ mean in Bash?

A regular expression matching sign, the =~ operator, is used to identify regular expressions. Perl has a similar operator for regular expression corresponding, which stimulated this operator.

What is =~?

The =~ operator is a regular expression match operator. This operator is inspired by Perl's use of the same operator for regular expression matching.


1 Answers

This approach has the advantage of not needing to loop over all the elements (at least not explicitly). But since array_to_string_internal() in array.c still loops over array elements and concatenates them into a string, it's probably not more efficient than the looping solutions proposed, but it's more readable.

if [[ " ${array[*]} " =~ " ${value} " ]]; then     # whatever you want to do when array contains value fi  if [[ ! " ${array[*]} " =~ " ${value} " ]]; then     # whatever you want to do when array doesn't contain value fi 

Note that in cases where the value you are searching for is one of the words in an array element with spaces, it will give false positives. For example

array=("Jack Brown") value="Jack" 

The regex will see "Jack" as being in the array even though it isn't. So you'll have to change IFS and the separator characters on your regex if you want still to use this solution, like this

IFS="|" array=("Jack Brown${IFS}Jack Smith") value="Jack"  if [[ "${IFS}${array[*]}${IFS}" =~ "${IFS}${value}${IFS}" ]]; then     echo "true" else     echo "false" fi  unset IFS # or set back to original IFS if previously set 

This will print "false".

Obviously this can also be used as a test statement, allowing it to be expressed as a one-liner

[[ " ${array[*]} " =~ " ${value} " ]] && echo "true" || echo "false" 
like image 84
Keegan Avatar answered Oct 14 '22 23:10

Keegan