Check if a Bash array contains a value

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

    given :

    array=("something to search for" "a string" "test2000")
    elem="a string"
    

    then a simple check of :

    if c=$'\x1E' && p="${c}${elem} ${c}" && [[ ! "${array[@]/#/${c}} ${c}" =~ $p ]]; then
      echo "$elem exists in array"
    fi
    

    where

    c is element separator
    p is regex pattern
    

    (The reason for assigning p separately, rather than using the expression directly inside [[ ]] is to maintain compatibility for bash 4)

提交回复
热议问题