Arithmetic Operators in Bash

Bash provides different operators that we can use in our Bash Script.

  • Arithmetic
  • Assignment
  • Bitwise
  • Logical
  • Relational

Arithmetic Operator

Bash provides multiple operations through which we can perform Mathematical/Arithmetic operations on variables.

OperatorDescription
+Addition
*Multiplication
-Subtraction
/Divison
%Modulo
**Exponentiation
+=Plus-Equal(Increments a Variable value)
*=Times-Equal(Multiply a Variable value)
-=Minus-Equal(Decrement a Variable value)
/=Slash-Equal(Divide a Variable Value)
%=Mod-Equal( Remainder of Dividing a Variable)

Let’s see some of the examples below.

# Addition 
~$ echo $[5+5]
10

# Subtraction
~$ echo $[ 10 -3 ]
7

# Multiplication
~$ echo $[ 10 * 3 ]
30

#  Division
~$ echo $[10/5]
2

# Modulus Operation
~$ echo $[10%5]
0

~$ echo $[10%3]
1

## Another way of using the internal Calulator.
~$ echo $((10 + 5 ))
15

Assignment Operator

Bash provides mainly equals to = as an assignment operator.

OperatorDescription
=Initialize/Change the value of the variable assigned

Bitwise Operator

Bitwise operators process bits or bit patterns, unlike other operators.

OperatorDescription
<<Bitwise Left Shift
<<==Left-Shift-Equal
>>Bitwise Right Shift
>>==Right-Shift-Equal
|Bitwise OR
|=Bitwise OR-Equal
&Bitwise AND
&=Bitwise OR-Equal
~Bitwise NOT
^Bitwise XOR
^= Bitwise XOR-Equal

Logical Operator

OperatorsDescription
!NOT
&&AND
||OR

Relational Operator

These Operators work on two operands or Variables and return True or False accordingly. Some of this operator like lt can be used in if statements.

OperatorDescription
== or -eqNot Equal. The result is True if two operands/variables is not equal, else gives a False
!= or -neLess Than. The result is true if the First Operand/Variable is less than the Second Operand,
else gives False
< or -ltEquals to. The result is True if two operands/variables are equal, else gives a False
<= or -leGreater than or equal. The result is true if the First Operand is greater than or Equal to the Operand Second
> or -gtLess than or equal. The result is true if the First Operand/Variable is less than or equals to
The second Operand, else Return False
>= or -geGreater than or equal. The result is true if the First Operand is greater than or Equal to the Operand Second
-ZChecks if the value of an operand is null or not

When we compare Strings, it is recommended to put the variables into double quotes " so that it minimizes the error if the variable is null or contains paces.

Example:

name1="nitendratech"
name2="nitendratech"

if [ "$name1" == "$name2" ]