woradin
woradin

Reputation: 43

How to check if all members of an array are equal to something in unix bash

Is there any method without a loop to check whether all members of the following arrays are equal to true?

found1=(true true true true);

found2=(true false true true);

Upvotes: 4

Views: 1864

Answers (3)

whoan
whoan

Reputation: 8521

You can use the [[ ]] operator. Here is a function based solution:

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

You can use it in this way:

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

OK will be displayed as a result if the condition satisfies

Upvotes: 5

nagendra547
nagendra547

Reputation: 6302

This is another very simple solution for your problem.

Here I am first checking that are all the elements are duplicates or not. If element is duplicate then

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

will have only one element. Hope it's clear.

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

Upvotes: 0

Hoshang Charania
Hoshang Charania

Reputation: 65

This is my first answer, don't pressurize me if I did not understand the question correctly.

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

OUTPUT:

true true true true

true false true true

I just used the and operator with a 3rd array which only consists of true. I also did not use any loops.

You can see that the first OUTPUT consists of all true elements because with the and operator only true and true gives true, whereas true and false(or false and false--> not possible in this case) will give you false.

Upvotes: 0

Related Questions