Check if a Bash array contains a value

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

    One-line solution

    printf '%s\n' "${myarray[@]}" | grep -P '^mypattern$'
    

    Explanation

    The printf statement prints each element of the array on a separate line.

    The grep statement uses the special characters ^ and $ to find a line that contains exactly the pattern given as mypattern (no more, no less).


    Usage

    To put this into an if ... then statement:

    if printf '%s\n' "${myarray[@]}" | grep -q -P '^mypattern$'; then
        # ...
    fi
    

    I added a -q flag to the grep expression so that it won't print matches; it will just treat the existence of a match as "true."

提交回复
热议问题