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

查看:248
本文介绍了检查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


对于关联数组,有一种非常整洁的方法来测试数组是否包含给定的 key :-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天全站免登陆