检查 Bash 数组是否包含值 [英] Check if a Bash array contains a value
问题描述
在 Bash 中,测试数组是否包含某个值的最简单方法是什么?
In Bash, what is the simplest way to test if an array contains a certain value?
推荐答案
这种方法的优点是不需要遍历所有元素(至少不是明确地).但是由于 array_to_string_internal()
在 array.c 仍然循环遍历数组元素并将它们连接成一个字符串,它可能不会比提出的循环解决方案更有效,但它更具可读性.
This approach has the advantage of not needing to loop over all the elements (at least not explicitly). But since array_to_string_internal()
in array.c still loops over array elements and concatenates them into a string, it's probably not more efficient than the looping solutions proposed, but it's more readable.
if [[ " ${array[*]} " =~ " ${value} " ]]; then
# whatever you want to do when array contains value
fi
if [[ ! " ${array[*]} " =~ " ${value} " ]]; then
# whatever you want to do when array doesn't contain value
fi
请注意,如果您要搜索的值是数组元素中带有空格的单词之一,则会产生误报.例如
Note that in cases where the value you are searching for is one of the words in an array element with spaces, it will give false positives. For example
array=("Jack Brown")
value="Jack"
正则表达式将看到Jack"作为在阵列中,即使它不是.因此,如果您仍想使用此解决方案,则必须更改 IFS
和正则表达式上的分隔符,就像这样
The regex will see "Jack" as being in the array even though it isn't. So you'll have to change IFS
and the separator characters on your regex if you want still to use this solution, like this
IFS="|"
array=("Jack Brown${IFS}Jack Smith")
value="Jack"
if [[ "${IFS}${array[*]}${IFS}" =~ "${IFS}${value}${IFS}" ]]; then
echo "true"
else
echo "false"
fi
unset IFS # or set back to original IFS if previously set
这将打印false".
This will print "false".
显然这也可以用作测试语句,允许它表示为单行
Obviously this can also be used as a test statement, allowing it to be expressed as a one-liner
[[ " ${array[*]} " =~ " ${value} " ]] && echo "true" || echo "false"
这篇关于检查 Bash 数组是否包含值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!