如何检查数组的所有成员是否等于unix bash中的某些内容

时间:2017-09-01 00:57:13

标签: arrays linux bash shell

是否有任何没有循环的方法来检查以下数组的所有成员是否等于true

found1=(true true true true);

found2=(true false true true);

3 个答案:

答案 0 :(得分:3)

您可以使用[[ ]]运算符。这是一个基于功能的解决方案:

check_true() {
    [[ "${*}" =~ ^(true )*true$ ]]
    return
}

您可以这样使用它:

$ found1=(true true true true)
$ found2=(true false true true)
$ check_true ${found1[*]} && echo OK
OK
$ check_true ${found2[*]} && echo OK
  如果条件满足

OK将显示为结果

答案 1 :(得分:0)

这是我的第一个答案,如果我没有正确理解这个问题,请不要给我压力。

found1=(true true true true)
found2=(true false true true)
found3=(true true true true)
     echo ${found1[*]} && ${found3[*]}
     echo ${found2[*]} && ${found3[*]}

输出:

true true true true

true false true true

我只使用了带有第3个数组的and运算符,该数组只包含true。我也没有使用任何循环。

你可以看到第一个OUTPUT由所有真元素组成,因为使用和运算符只有true而true给出true,而true和false(或false和false - >在这种情况下不可能)会给你false

答案 2 :(得分:0)

这是解决您问题的另一个非常简单的解决方案。

这里我首先检查所有元素是否重复。如果元素是重复的那么

echo "${array[@]}"  | tr ' ' '\n' | sort -u

只有一个元素。希望它清楚。

check_equal(){
array=$1
if [ `echo "${array[@]}"  | tr ' ' '\n' | sort -u | wc -l` = 1 ] && [ ${array[0]} = $2 ]
then echo "Equal";
else
echo "Not Equal" ; fi
}

found1=(true true true true);
found2=(true false true true);

check_equal ${found1[@]} true
check_equal ${found2[@]} true