E.g.
foo=(a b c)
Now, how can I do an easy check if b
is in $foo
?
array=(word "two words" words) search_string="two" match=$(echo "${array[@]:0}" | grep -o $search_string) [[ ! -z $match ]] && echo "found !"
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.
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
(( ${foo[(I)b]} )) \ && echo "it's in" \ || echo "it's somewhere else maybe"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With