<分区>
我想知道在 Bash 中是否有一种有效的方法来检查数组中是否存在元素?我正在寻找类似于我可以在 Python 中执行的操作,例如:
arr = ['a','b','c','d']
if 'd' in arr:
do your thing
else:
do something
我已经看到针对 Bash 4+ 的 bash 使用关联数组的解决方案,但我想知道是否还有其他解决方案。
请理解,我知道简单的解决方案是在数组中迭代,但我不想那样。
<分区>
我想知道在 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/44347800/