Total Page Views :-

## expr

expr command is used to perform shell arithmetic and evaluate expressions

### Syntax/Usage

expr expression

• 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.
``` Examples:- a=7 b=10 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)
``` Figure 1 ```
• 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

• 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.
``` Examples:- c=\$((a+b)) c=`expr \$a + \$((b*b*b))` c=\$((a+(b*b*b))) ```

Note:-

• 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 \$((…)) .