Check if a Bash array contains a value

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

    Using grep and printf

    Format each array member on a new line, then grep the lines.

    if printf '%s\n' "${array[@]}" | grep -x -q "search string"; then echo true; else echo false; fi
    
    example:
    $ array=("word", "two words")
    $ if printf '%s\n' "${array[@]}" | grep -x -q "two words"; then echo true; else echo false; fi
    true
    

    Note that this has no problems with delimeters and spaces.

提交回复
热议问题