在 bash 中的数组运算符中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5852446/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 23:54:03  来源:igfitidea点击:

In array operator in bash

arraysbashshell

提问by ???u

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

回答by Frank

A for loop will do the trick.

for 循环可以解决问题。

array=(one two three)

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

回答by pepoluan

Try this:

尝试这个:

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

回答by user unknown

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

我的 .bashrc 文件中有一个函数“包含”:

contains () 
{ 
    param=;
    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

回答by William Pursell

I like using grep for this:

我喜欢为此使用 grep:

if echo ${array[@]} | grep -qw one; then
  # "one" is in the array
  ...
fi

(Note that both -qand -ware non-standard options to grep: -wtells it to work on whole words only, and -q("quiet") suppresses all output.)

(请注意,-q-w都是 grep 的非标准选项:-w告诉它只处理整个单词,并且-q("quiet") 抑制所有输出。)

回答by Szépe Viktor

In_array() {
    local NEEDLE=""
    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.

上面的一个漂亮而优雅的版本。

回答by drysdam

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.

如果这很丑陋,您可以将其隐藏在函数中。

回答by ghostdog74

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