Check if a Bash array contains a value

前端 未结 30 2764
执笔经年
执笔经年 2020-11-22 07:14

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

30条回答
  •  一个人的身影
    2020-11-22 07:50

    I generally write these kind of utilities to operate on the name of the variable, rather than the variable value, primarily because bash can't otherwise pass variables by reference.

    Here's a version that works with the name of the array:

    function array_contains # array value
    {
        [[ -n "$1" && -n "$2" ]] || {
            echo "usage: array_contains  "
            echo "Returns 0 if array contains value, 1 otherwise"
            return 2
        }
    
        eval 'local values=("${'$1'[@]}")'
    
        local element
        for element in "${values[@]}"; do
            [[ "$element" == "$2" ]] && return 0
        done
        return 1
    }
    

    With this, the question example becomes:

    array_contains A "one" && echo "contains one"
    

    etc.

提交回复
热议问题