检查Bash数组是否包含值 [英] Check if a Bash array contains a value

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

问题描述

在Bash中,最简单的测试数组是否包含特定值的方法是什么?

In Bash, what is the simplest way to test if an array contains a certain value?

编辑:在答案和评论的帮助下,经过一些测试,我想到了:

Edit: With help from the answers and the comments, after some testing, I came up with this:

function contains() {
    local n=$#
    local value=${!n}
    for ((i=1;i < $#;i++)) {
        if [ "${!i}" == "${value}" ]; then
            echo "y"
            return 0
        fi
    }
    echo "n"
    return 1
}

A=("one" "two" "three four")
if [ $(contains "${A[@]}" "one") == "y" ]; then
    echo "contains one"
fi
if [ $(contains "${A[@]}" "three") == "y" ]; then
    echo "contains three"
fi

我不确定这是否是最好的解决方案,但似乎可行.

I'm not sure if it's the best solution, but it seems to work.

推荐答案

此方法的优点是不需要遍历所有元素(至少不是显式地).但是,由于 array.c 中的array_to_string_internal()仍然循环遍历数组元素并将它们连接成字符串,它可能不比所提出的循环解决方案更有效,但更具可读性.

This approach has the advantage of not needing to loop over all the elements (at least not explicitly). But since array_to_string_internal() in array.c still loops over array elements and concatenates them into a string, it's probably not more efficient than the looping solutions proposed, but it's more readable.

if [[ " ${array[@]} " =~ " ${value} " ]]; then
    # whatever you want to do when array contains value
fi

if [[ ! " ${array[@]} " =~ " ${value} " ]]; then
    # whatever you want to do when array doesn't contain value
fi

请注意,如果您要搜索的值是带有空格的数组元素中的单词之一,则会产生误报.例如

Note that in cases where the value you are searching for is one of the words in an array element with spaces, it will give false positives. For example

array=("Jack Brown")
value="Jack"

即使不是,正则表达式也会看到"Jack"在数组中.因此,如果您仍想使用这种解决方案,则必须更改IFS和正则表达式上的分隔符,例如

The regex will see "Jack" as being in the array even though it isn't. So you'll have to change IFS and the separator characters on your regex if you want still to use this solution, like this

IFS=$'\t'
array=("Jack Brown\tJack Smith")
unset IFS
value="Jack"

if [[ "\t${array[@]}\t" =~ "\t${value}\t" ]]; then
    echo "true"
else
    echo "false"
fi

这将显示"false".

This will print "false".

很明显,这也可以用作测试语句,允许将其表示为单行格式

Obviously this can also be used as a test statement, allowing it to be expressed as a one-liner

[[ " ${array[@]} " =~ " ${value} " ]] && echo "true" || echo "false"

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

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