In Bash, what is the simplest way to test if an array contains a certain value?
Borrowing from Dennis Williamson's answer, the following solution combines arrays, shell-safe quoting, and regular expressions to avoid the need for: iterating over loops; using pipes or other sub-processes; or using non-bash utilities.
declare -a array=('hello, stack' one 'two words' words last)
printf -v array_str -- ',,%q' "${array[@]}"
if [[ "${array_str},," =~ ,,words,, ]]
then
echo 'Matches'
else
echo "Doesn't match"
fi
The above code works by using Bash regular expressions to match against a stringified version of the array contents. There are six important steps to ensure that the regular expression match can't be fooled by clever combinations of values within the array:
printf
shell-quoting, %q
. Shell-quoting will ensure that special characters become "shell-safe" by being escaped with backslash \
.%q
; that's the only way to guarantee that values within the array can't be constructed in clever ways to fool the regular expression match. I choose comma ,
because that character is the safest when eval'd or misused in an otherwise unexpected way.,,%q
as the argument to printf
. This is important because two instances of the special character can only appear next to each other when they appear as the delimiter; all other instances of the special character will be escaped.${array_str}
, compare against ${array_str},,
.