In array operator in bash

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

    Try this:

    array=(one two three)
    if [[ "${array[*]}" =~ "one" ]]; then
      echo "'one' is found"
    fi
    
    0 讨论(0)
  • 2021-02-19 22:27

    if you just want to check whether an element is in array, another approach

    case "${array[@]/one/}" in 
     "${array[@]}" ) echo "not in there";;
     *) echo "found ";;
    esac
    
    0 讨论(0)
  • 2021-02-19 22:31

    A for loop will do the trick.

    array=(one two three)
    
    for i in "${array[@]}"; do
      if [[ "$i" = "one" ]]; then
        ...
        break
      fi
    done
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-02-19 22:33
    OPTIONS=('-q','-Q','-s','-S')
    
    find="$(grep "\-q" <<< "${OPTIONS[@]}")"
    if [ "$find" = "${OPTIONS[@]}" ];
    then
        echo "arr contains -q"
    fi
    
    0 讨论(0)
  • 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.)

    0 讨论(0)
提交回复
热议问题