In Bash, what is the simplest way to test if an array contains a certain value?
A small addition to @ghostdog74's answer about using case
logic to check that array contains particular value:
myarray=(one two three)
word=two
case "${myarray[@]}" in ("$word "*|*" $word "*|*" $word") echo "found" ;; esac
Or with extglob
option turned on, you can do it like this:
myarray=(one two three)
word=two
shopt -s extglob
case "${myarray[@]}" in ?(*" ")"$word"?(" "*)) echo "found" ;; esac
Also we can do it with if
statement:
myarray=(one two three)
word=two
if [[ $(printf "_[%s]_" "${myarray[@]}") =~ .*_\[$word\]_.* ]]; then echo "found"; fi