Check if a Bash array contains a value

前端 未结 30 2412
执笔经年
执笔经年 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 08:10

    This is working for me:

    # traditional system call return values-- used in an `if`, this will be true when returning 0. Very Odd.
    contains () {
        # odd syntax here for passing array parameters: http://stackoverflow.com/questions/8082947/how-to-pass-an-array-to-a-bash-function
        local list=$1[@]
        local elem=$2
    
        # echo "list" ${!list}
        # echo "elem" $elem
    
        for i in "${!list}"
        do
            # echo "Checking to see if" "$i" "is the same as" "${elem}"
            if [ "$i" == "${elem}" ] ; then
                # echo "$i" "was the same as" "${elem}"
                return 0
            fi
        done
    
        # echo "Could not find element"
        return 1
    }
    

    Example call:

    arr=("abc" "xyz" "123")
    if contains arr "abcx"; then
        echo "Yes"
    else
        echo "No"
    fi
    

提交回复
热议问题