In array operator in bash

前端 未结 9 1752
无人及你
无人及你 2021-02-19 22:20

Is there a way to test whether an array contains a specified element?

e.g., something like:

array=(one two three)

if [ \"one\" in ${array} ]; then
...
f         


        
9条回答
  •  广开言路
    2021-02-19 22:38

    I like using grep for this:

    if echo ${array[@]} | grep -qw one; then
      # "one" is in the array
      ...
    fi
    

    (Note that both -q and -w are non-standard options to grep: -w tells it to work on whole words only, and -q ("quiet") suppresses all output.)

提交回复
热议问题