In array operator in bash

前端 未结 9 1892
无人及你
无人及你 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:39
    in_array() {
        local needle=$1 el
        shift
        for el in "$@"; do
            if [ "$el" = "$needle" ]; then
                return 0
            fi
        done
        return 1
    }
    
    if in_array 1 1 2 3; then
        echo true
    else
        echo false
    fi
    
    # alternatively
    a=(1 2 3)
    if in_array 1 "${a[@]}"; then
    ...
    
    0 讨论(0)
  • 2021-02-19 22:43
    array="one two three"
    if [ $(echo "$array" | grep one | wc -l) -gt 0 ] ; 
      then echo yes; 
    fi
    

    If that's ugly, you could hide it away in a function.

    0 讨论(0)
  • 2021-02-19 22:48
    In_array() {
        local NEEDLE="$1"
        local ELEMENT
    
        shift
    
        for ELEMENT; do
            if [ "$ELEMENT" == "$NEEDLE" ]; then
                return 0
            fi
        done
    
        return 1
    }
    
    declare -a ARRAY=( "elem1" "elem2" "elem3" )
    if In_array "elem1" "${ARRAY[@]}"; then
    ...
    

    A nice and elegant version of the above.

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