In Bash, what is the simplest way to test if an array contains a certain value?
The answer with most votes is very concise and clean, but it can have false positives when a space is part of one of the array elements. This can be overcome when changing IFS and using "${array[*]}"
instead of "${array[@]}"
. The method is identical, but it looks less clean. By using "${array[*]}"
, we print all elements of $array
, separated by the first character in IFS
. So by choosing a correct IFS
, you can overcome this particular issue. In this particular case, we decide to set IFS
to an uncommon character $'\001'
which stands for Start of Heading (SOH)
$ array=("foo bar" "baz" "qux")
$ IFS=$'\001'
$ [[ "$IFS${array[*]}$IFS" =~ "${IFS}foo${IFS}" ]] && echo yes || echo no
no
$ [[ "$IFS${array[*]}$IFS" =~ "${IFS}foo bar${IFS}" ]] && echo yes || echo no
yes
$ unset IFS
This resolves most issues false positives, but requires a good choice of IFS
.
note: If IFS
was set before, it is best to save it and reset it instead of using unset IFS
related: