有没有办法测试数组是否包含指定的元素?
例如,像:array=(one two three)
if [ "one" in ${array} ]; then
...
fi
答案 0 :(得分:22)
for循环可以解决问题。
array=(one two three)
for i in "${array[@]}"; do
if [[ "$i" = "one" ]]; then
...
break
fi
done
答案 1 :(得分:7)
试试这个:
array=(one two three)
if [[ "${array[*]}" =~ "one" ]]; then
echo "'one' is found"
fi
答案 2 :(得分:4)
我的.bashrc文件中有一个'contains'函数:
contains ()
{
param=$1;
shift;
for elem in "$@";
do
[[ "$param" = "$elem" ]] && return 0;
done;
return 1
}
它适用于数组:
contains on $array && echo hit || echo miss
miss
contains one $array && echo hit || echo miss
hit
contains onex $array && echo hit || echo miss
miss
但不需要数组:
contains one four two one zero && echo hit || echo miss
hit
答案 3 :(得分:1)
我喜欢用grep:
if echo ${array[@]} | grep -qw one; then
# "one" is in the array
...
fi
(请注意,-q
和-w
都是grep的非标准选项:-w
告诉它只处理整个单词,-q
(“安静” )抑制所有输出。)
答案 4 :(得分:0)
array="one two three"
if [ $(echo "$array" | grep one | wc -l) -gt 0 ] ;
then echo yes;
fi
如果这很难看,你可以将它隐藏在一个函数中。
答案 5 :(得分:0)
如果你只想检查一个元素是否在数组中,另一种方法
case "${array[@]/one/}" in
"${array[@]}" ) echo "not in there";;
*) echo "found ";;
esac
答案 6 :(得分:0)
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
...
以上的优雅版本。
答案 7 :(得分:0)
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
...
答案 8 :(得分:-1)
OPTIONS=('-q','-Q','-s','-S')
find="$(grep "\-q" <<< "${OPTIONS[@]}")"
if [ "$find" = "${OPTIONS[@]}" ];
then
echo "arr contains -q"
fi