1

How to return True if only one variable of three is True in BASH?

I have three boolean variables:

a|b|c|
1 1 1 False
1 1 0 False
1 0 1 False
1 0 0 True
0 1 1 False
0 1 0 True
0 0 1 True
0 0 0 False

I need a logical expression that returt true only if one variable is true. I try with

if  [[ ( $a == 1 || $b == 1 || $c == 1 ) && ( $a == 1  &&  $b == 1  &&  $c == 1 ) ]];  then
  return True
fi

Thank you

karmax
  • 171
  • 2
  • 13

2 Answers2

7

You can just sum the values and check whether the result equals 1.

Here, I'm using an arithmetic expression to sum the numbers and check the equality.

#! /bin/bash
for a in 0 1 ; do
    for b in 0 1 ; do
        for c in 0 1 ; do
            printf '%s ' $a $b $c
            (( 1 == a + b + c )) && echo True || echo False
        done
    done
done
choroba
  • 231,213
  • 25
  • 204
  • 289
1

This is the logic which i collected (a^b^c) & ~(a&b&c)

xor all values and remove the case where all values of abc are true truth table

a b c f = a^b^c g = ~(a&b&c) h = f&g

0 0 0 0 1 0

0 0 1 1 1 1

0 1 0 1 1 1

0 1 1 0 1 0

1 0 0 1 1 1

1 0 1 0 1 0

1 1 0 0 1 0

1 1 1 1 0 0

here f is the xor of a b and c and g is the negation of a&b&c the output produces only when one value is true

Have a nice day

Rahul Somaraj
  • 251
  • 2
  • 9