1

There are 20 questions/answers about how to perform boolean operations in conditions:

if [ 4 -gt 3 ] && [ 3 -gt 2 ]; then echo "True"; else echo "False"; fi

But how to perform boolean operations standalone?

I am looking for something equivalent to following code:

bool a=true, b=false, c=true;
bool r1 = a && b;
bool r2 = a && (b || c);

In bash, it should be something like:

a=1;b=0;c=1
r1=`expr a && b`
r2=`expr a && ( b || c )`

1 Answer 1

4

use $(( )) construction

in man bash see 'ARITHMETIC EVALUATION'

The shell allows arithmetic expressions to be evaluated, under certain circumstances (see the let and declare builtin commands, the (( compound command, and Arithmetic Expansion).

r1=$((a && b))
r2=$((a && ( b || c )))
echo $1
0
echo $2
1

note

  • that & is bitwise, while && is logical

  • 0 and ≠0 revert to traditionnal/mathematical 0/false and ≠0/true value (unlike unix return code)

     b=$(( 7 & 5 ))
     echo $b
     5
     l=$(( 7 && 5 ))
     echo $l
     1
    
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.