Check if a Bash array contains a value

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

    After having answered, I read another answer that I particularly liked, but it was flawed and downvoted. I got inspired and here are two new approaches I see viable.

    array=("word" "two words") # let's look for "two words"
    

    using grep and printf:

    (printf '%s\n' "${array[@]}" | grep -x -q "two words") && 
    

    using for:

    (for e in "${array[@]}"; do [[ "$e" == "two words" ]] && exit 0; done; exit 1) && 
    

    For not_found results add ||

提交回复
热议问题