Check if a Bash array contains a value

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

    If you need performance, you don't want to loop over your whole array every time you search.

    In this case, you can create an associative array (hash table, or dictionary) that represents an index of that array. I.e. it maps each array element into its index in the array:

    make_index () {
      local index_name=$1
      shift
      local -a value_array=("$@")
      local i
      # -A means associative array, -g means create a global variable:
      declare -g -A ${index_name}
      for i in "${!value_array[@]}"; do
        eval ${index_name}["${value_array[$i]}"]=$i
      done
    }
    

    Then you can use it like this:

    myarray=('a a' 'b b' 'c c')
    make_index myarray_index "${myarray[@]}"
    

    And test membership like so:

    member="b b"
    # the "|| echo NOT FOUND" below is needed if you're using "set -e"
    test "${myarray_index[$member]}" && echo FOUND || echo NOT FOUND
    

    Or also:

    if [ "${myarray_index[$member]}" ]; then 
      echo FOUND
    fi
    

    Notice that this solution does the right thing even if the there are spaces in the tested value or in the array values.

    As a bonus, you also get the index of the value within the array with:

    echo "<< ${myarray_index[$member]} >> is the index of $member"
    

提交回复
热议问题