expr command is used to perform shell arithmetic and evaluate expressions
Variables defined in Linux bash shell stores values in the form of string.
Integers are also stored as strings
So to perform arithmetic operation on such variables ‘expr’ command is used.
expr $a + $b // output: 17
c=`expr $a – 4` //result 3 is stored in variable ‘c’
echo `expr $b % $a` //remainder 3 is printed
Note: Notice space on either side of the ‘+’ operator .
To access the value of value of ‘a’ and ‘b’ variable use ‘$’ symbol as prefix to variables.
Use back tick ( ` ) for command substitution i.e using one command in the other. (Back tick is found above the tab key on your PC keyboard)
Supported arithmetic operators are +, - , * , /, %
The operator ‘*’ must be preceded by a ‘\’backslash character else it will be considered as a wildcard character.
expr $a \* $b
Using brackets ( ) in expr command gives an error.
Alternative Way of arithmetic expression
Another way to calculate the arithmetic expression is to enclose the expression in $((…))
This way of evaluation let us make use of brackets as in normal mathematics.
c=`expr $a + $((b*b*b))`
Here there is no space on either side of the operator
To access the value of variables no need of using ‘$’ sign separately again and again for each variable
‘*’ operator does not need to be preceded with backslash
Double brackets preceded with ‘$’ symbol are must i.e $((…)) .