Check if a Bash array contains a value

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

    Below is a small function for achieving this. The search string is the first argument and the rest are the array elements:

    containsElement () {
      local e match="$1"
      shift
      for e; do [[ "$e" == "$match" ]] && return 0; done
      return 1
    }
    

    A test run of that function could look like:

    $ array=("something to search for" "a string" "test2000")
    $ containsElement "a string" "${array[@]}"
    $ echo $?
    0
    $ containsElement "blaha" "${array[@]}"
    $ echo $?
    1
    

提交回复
热议问题