这个问题在这里已经有了答案:
Check if a Bash array contains a value
(39 个回答)
11 个月前关闭。
我想知道是否有一种有效的方法来检查 Bash 中的数组中是否存在元素?我正在寻找类似于我在 Python 中可以做的事情,例如:
arr = ['a','b','c','d']
if 'd' in arr:
do your thing
else:
do something
我已经看到针对 Bash 4+ 的 bash 使用关联数组的解决方案,但我想知道是否还有其他解决方案。
请理解,我知道简单的解决方案是在数组中迭代,但我不想要那样。
最佳答案
你可以这样做:
if [[ " ${arr[*]} " == *" d "* ]]; then
echo "arr contains d"
fi
例如,如果您查找“a b”,这将产生误报——该子字符串在连接字符串中,但不是作为数组元素。无论您选择什么分隔符,都会出现这种困境。
最安全的方法是遍历数组直到找到元素:
array_contains () {
local seeking=$1; shift
local in=1
for element; do
if [[ $element == "$seeking" ]]; then
in=0
break
fi
done
return $in
}
arr=(a b c "d e" f g)
array_contains "a b" "${arr[@]}" && echo yes || echo no # no
array_contains "d e" "${arr[@]}" && echo yes || echo no # yes
这是一个“更干净”的版本,您只需传递数组名称,而不是它的所有元素
array_contains2 () {
local array="$1[@]"
local seeking=$2
local in=1
for element in "${!array}"; do
if [[ $element == "$seeking" ]]; then
in=0
break
fi
done
return $in
}
array_contains2 arr "a b" && echo yes || echo no # no
array_contains2 arr "d e" && echo yes || echo no # yes
对于关联数组,有一种非常简洁的方法来测试数组是否包含给定的键:
-v
运算符$ declare -A arr=( [foo]=bar [baz]=qux )
$ [[ -v arr[foo] ]] && echo yes || echo no
yes
$ [[ -v arr[bar] ]] && echo yes || echo no
no
参见手册中的 6.4 Bash Conditional Expressions。
关于arrays - 检查元素是否存在于 Bash 数组中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14366390/