Advanced Comparisons

Double Parentheses

The double parentheses command allows you to incorporate advanced mathematical formulas in your comparisons.

Symbol Description Example
val++

Post-increment

Interpret the value of integer variable val and then add one (1) to it.

val=5
(( val++ ))
echo $val
val--

Post-decrement

Interpret the value of integer variable val and then subtract one (1) from it.

val=5
(( val-- ))
echo $val
++val

Pre-increment

Add one (1) to the value of integer variable val, and then interpret the value.

val=5
(( ++val ))
echo $val
--val

Pre-decrement

Subtract one (1) from the value of integer variable val, and then interpret the value.

val=5
(( --val ))
echo $val
!

Logical negation

Logical negation returns false if its operand is true, and true if the operand is false.

echo $(( ! 1 )) # this will echo 0 
echo $(( ! 0 )) # this will echo 1
~

Bitwise negation

Bitwise negation flips the bits in the binary representation of the numeric operand.

echo $(( ~ 3 )) # will return -4
** Exponentiation
echo $(( 4 ** 2 )) # will square 4 = 16
<< Left bitwise shift
echo $(( 0xDEADBEEF << 0x12345678 ))
>> right bitwise shift
echo $(( 0x12345678 >> 0xDEADBEEF ))
&

bitwise AND

The corresponding binary digits of both operands are multiplied to produce a result; for any given digit, the resulting digit is 1 if and only if the corresponding digit in both operands is also 1.

echo $(( 0x12345678 & 0xDEADBEEF ))
| Bitwise OR
If either of the corresponding digits in the operands is 1, that digit in the result will also be 1.
echo $(( 0x12345678 | 0xDEADBEEF ))
&&
Logical AND
Returns true if both of the operands are true.
echo $(( 1 == 1 && 3 == 3 )) # will return 1
|| Logical OR
Returns true if either of the operands is true.
echo $(( 1 == 2 || 3 == 3 )) # will return 1