我想知道是否有一种有效的方法来检查 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
For 关联数组,有一个非常简洁的方法来测试数组是否包含给定的key: The -v
操作员
$ declare -A arr=( [foo]=bar [baz]=qux )
$ [[ -v arr[foo] ]] && echo yes || echo no
yes
$ [[ -v arr[bar] ]] && echo yes || echo no
no
See 6.4 Bash 条件表达式 https://www.gnu.org/software/bash/manual/bash.html#Bash-Conditional-Expressions在手册中。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)