Check if a Bash array contains a value

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

    A small addition to @ghostdog74's answer about using case logic to check that array contains particular value:

    myarray=(one two three)
    word=two
    case "${myarray[@]}" in  ("$word "*|*" $word "*|*" $word") echo "found" ;; esac
    

    Or with extglob option turned on, you can do it like this:

    myarray=(one two three)
    word=two
    shopt -s extglob
    case "${myarray[@]}" in ?(*" ")"$word"?(" "*)) echo "found" ;; esac
    

    Also we can do it with if statement:

    myarray=(one two three)
    word=two
    if [[ $(printf "_[%s]_" "${myarray[@]}") =~ .*_\[$word\]_.* ]]; then echo "found"; fi
    

提交回复
热议问题