Check if a Bash array contains a value

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

    Combining a few of the ideas presented here you can make an elegant if statment without loops that does exact word matches.

    find="myword"
    array=(value1 value2 myword)
    if [[ ! -z $(printf '%s\n' "${array[@]}" | grep -w $find) ]]; then
      echo "Array contains myword";
    fi
    

    This will not trigger on word or val, only whole word matches. It will break if each array value contains multiple words.

提交回复
热议问题