In array operator in bash

2019-04-21 07:28发布

问题:

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
...
fi

回答1:

A for loop will do the trick.

array=(one two three)

for i in "${array[@]}"; do
  if [[ "$i" = "one" ]]; then
    ...
    break
  fi
done


回答2:

Try this:

array=(one two three)
if [[ "${array[*]}" =~ "one" ]]; then
  echo "'one' is found"
fi


回答3:

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


回答4:

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.)



回答5:

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.



回答6:

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


回答7:

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.