Check if a Bash array contains a value

前端 未结 30 2415
执笔经年
执笔经年 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:46

    The OP added the following answer themselves, with the commentary:

    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
    

提交回复
热议问题