In array operator in bash

2019-04-21 06:59发布

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

7条回答
Luminary・发光体
2楼-- · 2019-04-21 07:34
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.

查看更多
The star\"
3楼-- · 2019-04-21 07:36

A for loop will do the trick.

array=(one two three)

for i in "${array[@]}"; do
  if [[ "$i" = "one" ]]; then
    ...
    break
  fi
done
查看更多
劳资没心,怎么记你
4楼-- · 2019-04-21 07:44

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
查看更多
爱情/是我丢掉的垃圾
5楼-- · 2019-04-21 07:44

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
查看更多
狗以群分
6楼-- · 2019-04-21 07:49
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.

查看更多
叛逆
7楼-- · 2019-04-21 07:53

Try this:

array=(one two three)
if [[ "${array[*]}" =~ "one" ]]; then
  echo "'one' is found"
fi
查看更多
登录 后发表回答