Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

zsh: check if string is in array

Tags:

arrays

zsh

E.g.

foo=(a b c) 

Now, how can I do an easy check if b is in $foo?

like image 536
Albert Avatar asked Mar 05 '11 11:03

Albert


People also ask

How do you check if a string is present in array in bash?

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 an element is present in an array in bash?

To find the index of specified element in an array in Bash, use For loop to iterate over the index of this array. In the for loop body, check if the current element is equal to the specified element. If there is a match, we may break the For loop and we have found index of first occurrence of specified element.


2 Answers

You can use reverse subscripting:

pax$ foo=(a b c)  pax$ if [[ ${foo[(r)b]} == b ]] ; then ; echo yes ; else ; echo no ; fi yes  pax$ if [[ ${foo[(r)x]} == x ]] ; then ; echo yes ; else ; echo no ; fi no 

You'll find the datails under man zshparam under Subscript Flags (at least in zsh 4.3.10 under Ubuntu 10.10).


Alternatively (thanks to geekosaur for this), you can use:

pax$ if [[ ${foo[(i)b]} -le ${#foo} ]] ; then ; echo yes ; else ; echo no ; fi 

You can see what you get out of those two expressions by simply doing:

pax$ echo ${foo[(i)a]} ${#foo} 1 3  pax$ echo ${foo[(i)b]} ${#foo} 2 3  pax$ echo ${foo[(i)c]} ${#foo} 3 3  pax$ echo ${foo[(i)d]} ${#foo} 4 3 
like image 73
paxdiablo Avatar answered Oct 05 '22 23:10

paxdiablo


(( ${foo[(I)b]} )) \   && echo "it's in" \   || echo "it's somewhere else maybe" 
like image 25
blueyed Avatar answered Oct 06 '22 01:10

blueyed