In array operator in bash

前端 未结 9 1922
无人及你
无人及你 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:48

    In_array() {
        local NEEDLE="$1"
        local ELEMENT
    
        shift
    
        for ELEMENT; do
            if [ "$ELEMENT" == "$NEEDLE" ]; then
                return 0
            fi
        done
    
        return 1
    }
    
    declare -a ARRAY=( "elem1" "elem2" "elem3" )
    if In_array "elem1" "${ARRAY[@]}"; then
    ...
    

    A nice and elegant version of the above.

提交回复
热议问题