Check if a Bash array contains a value

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

    The following code checks if a given value is in the array and returns its zero-based offset:

    A=("one" "two" "three four")
    VALUE="two"
    
    if [[ "$(declare -p A)" =~ '['([0-9]+)']="'$VALUE'"' ]];then
      echo "Found $VALUE at offset ${BASH_REMATCH[1]}"
    else
      echo "Couldn't find $VALUE"
    fi
    

    The match is done on the complete values, therefore setting VALUE="three" would not match.

提交回复
热议问题