In array operator in bash

前端 未结 9 1919
无人及你
无人及你 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:32

    I got an function 'contains' in my .bashrc-file:

    contains () 
    { 
        param=$1;
        shift;
        for elem in "$@";
        do
            [[ "$param" = "$elem" ]] && return 0;
        done;
        return 1
    }
    

    It works well with an array:

    contains on $array && echo hit || echo miss
      miss
    contains one $array && echo hit || echo miss
      hit
    contains onex $array && echo hit || echo miss
      miss
    

    But doesn't need an array:

    contains one four two one zero && echo hit || echo miss
      hit
    

提交回复
热议问题