在Bash中,测试数组是否包含某个值的最简单方法是什么?
当前回答
a=(b c d)
if printf '%s\0' "${a[@]}" | grep -Fqxz c
then
echo 'array “a” contains value “c”'
fi
如果你喜欢,你可以使用相同的长选项:
--fixed-strings --quiet --line-regexp --null-data
其他回答
containsElement () { for e in "${@:2}"; do [[ "$e" = "$1" ]] && return 0; done; return 1; }
现在正确处理空数组。
如果你不想重复,这是值得研究的:
#!/bin/bash
myarray=("one" "two" "three");
wanted="two"
if `echo ${myarray[@]/"$wanted"/"WAS_FOUND"} | grep -q "WAS_FOUND" ` ; then
echo "Value was found"
fi
exit
片段改编自:http://www.thegeekstuff.com/2010/06/bash-array-tutorial/ 我认为这很聪明。
编辑: 你可以这样做:
if `echo ${myarray[@]} | grep -q "$wanted"` ; then
echo "Value was found"
fi
但后者仅在数组包含唯一值时有效。我认为,在143中寻找1只会给出假阳性。
保持简单:
Array1=( "item1" "item2" "item3" "item-4" )
var="item3"
count=$(echo ${Array1[@]} | tr ' ' '\n' | awk '$1 == "'"$var"'"{print $0}' | wc -l)
[ $count -eq 0 ] && echo "Not found" || echo "found"
The answer with most votes is very concise and clean, but it can have false positives when a space is part of one of the array elements. This can be overcome when changing IFS and using "${array[*]}" instead of "${array[@]}". The method is identical, but it looks less clean. By using "${array[*]}", we print all elements of $array, separated by the first character in IFS. So by choosing a correct IFS, you can overcome this particular issue. In this particular case, we decide to set IFS to an uncommon character $'\001' which stands for Start of Heading (SOH)
$ array=("foo bar" "baz" "qux")
$ IFS=$'\001'
$ [[ "$IFS${array[*]}$IFS" =~ "${IFS}foo${IFS}" ]] && echo yes || echo no
no
$ [[ "$IFS${array[*]}$IFS" =~ "${IFS}foo bar${IFS}" ]] && echo yes || echo no
yes
$ unset IFS
这解决了大多数假阳性问题,但需要一个好的IFS选择。
注意:如果之前设置了IFS,最好保存并重新设置,而不是使用未设置的IFS
相关:
访问bash命令行参数$@ vs $*
另一个没有函数的代码:
(for e in "${array[@]}"; do [[ "$e" == "searched_item" ]] && exit 0; done) && echo "found" || echo "not found"
谢谢@Qwerty关于空格的提示!
对应的功能:
find_in_array() {
local word=$1
shift
for e in "$@"; do [[ "$e" == "$word" ]] && return 0; done
return 1
}
例子:
some_words=( these are some words )
find_in_array word "${some_words[@]}" || echo "expected missing! since words != word"