检查元素是否存在于 Bash 数组中 [英] Check if an element is present in a Bash array

查看:39
本文介绍了检查元素是否存在于 Bash 数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有一种有效的方法可以检查 Bash 中的数组中是否存在元素?我正在寻找类似于我在 Python 中可以做的事情,例如:

I was wondering if there is an efficient way to check if an element is present within an array in Bash? I am looking for something similar to what I can do in Python, like:

arr = ['a','b','c','d']

if 'd' in arr:
    do your thing
else:
    do something

我已经看到针对 Bash 4+ 的 bash 使用关联数组的解决方案,但我想知道是否还有其他解决方案.

I've seen solutions using associative array for bash for Bash 4+, but I am wondering if there is another solution out there.

请理解,我知道简单的解决方案是在数组中迭代,但我不想要那样.

Please understand that I know the trivial solution is to iterate in the array, but I don't want that.

推荐答案

你可以这样做:

if [[ " ${arr[*]} " == *" d "* ]]; then
    echo "arr contains d"
fi

例如,如果您查找a b",这将产生误报——该子字符串在连接字符串中,但不是作为数组元素.无论您选择何种分隔符,都会出现这种困境.

This will give false positives for example if you look for "a b" -- that substring is in the joined string but not as an array element. This dilemma will occur for whatever delimiter you choose.

最安全的方法是遍历数组直到找到元素:

The safest way is to loop over the array until you find the element:

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

这是一个更干净"的版本,您只需传递数组名称,而不是它的所有元素

Here's a "cleaner" version where you just pass the array name, not all its elements

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 运算符


For associative arrays, there's a very tidy way to test if the array contains a given key: The -v operator

$ 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 条件表达式手册.

这篇关于检查元素是否存在于 Bash 数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆