Check if a Bash array contains a value

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

    Here is my take on this problem. Here is the short version:

    function arrayContains() {
            local haystack=${!1}
            local needle="$2"
            printf "%s\n" ${haystack[@]} | grep -q "^$needle$"
    }
    

    And the long version, which I think is much easier on the eyes.

    # With added utility function.
    function arrayToLines() {
            local array=${!1}
            printf "%s\n" ${array[@]}
    }
    
    function arrayContains() {
            local haystack=${!1}
            local needle="$2"
            arrayToLines haystack[@] | grep -q "^$needle$"
    }
    

    Examples:

    test_arr=("hello" "world")
    arrayContains test_arr[@] hello; # True
    arrayContains test_arr[@] world; # True
    arrayContains test_arr[@] "hello world"; # False
    arrayContains test_arr[@] "hell"; # False
    arrayContains test_arr[@] ""; # False
    

提交回复
热议问题