Suppose I have a non-associative array that has been defined like
my_array=(foo bar baz)
How can I check whether the array contains a given string? I’d prefer a solution that can be used within the conditional of an if
block (e.g. if contains $my_array "something"; then ...
).
Best Answer
$array[(I)foo]
returns the index of the last occurrence offoo
in$array
and 0 if not found. Thee
flag is for it to be ane
xact match instead of a pattern match.To check the
$value
is among a literal list of values, you could pass that list of values to an anonymous function and look for the$value
in$@
in the body of the function:To know how many times the value is found in the array, you could use the
${A:*B}
operator (elements of arrayA
that are also in arrayB
):