In array operator in bash

前端 未结 9 1967
无人及你
无人及你 2021-02-19 22:20

Is there a way to test whether an array contains a specified element?

e.g., something like:

array=(one two three)

if [ \"one\" in ${array} ]; then
...
f         


        
9条回答
  •  无人及你
    2021-02-19 22:39

    in_array() {
        local needle=$1 el
        shift
        for el in "$@"; do
            if [ "$el" = "$needle" ]; then
                return 0
            fi
        done
        return 1
    }
    
    if in_array 1 1 2 3; then
        echo true
    else
        echo false
    fi
    
    # alternatively
    a=(1 2 3)
    if in_array 1 "${a[@]}"; then
    ...
    

提交回复
热议问题