Beginners Guide to Arithmetic Operations on Bourne Shell Variables
The Bourne shell assigns string values to variables only in the assignment statement. The Bourne shell has no built-in ability to perform arithmetic. The external statement, expr, treat the variables as numbers and performs the arithmetic operation.
**NOTE:**The expr statement is space-sensitive and expects each operand and operator to be separated by white spaces.
The expr statement recognizes the operators shown in the table below.
|+||Addition||num2=`expr “$num1” + 25`|
|-||Subtraction||num3=`expr “$num1” - “$num2”`|
|*||Multiplication||num3=`expr “$num1” \* “$num2”`|
|/||Division||num4=`expr “$num2” / “$num1”`|
|%||Integer remainder||num5=`expr “$num1” % 3`|
**NOTE:**Precede a multiplication operator with a backslash because it is a shell metacharacter.
The Bourne shell has no built-in arithmetic capability.
$ num1=5 $ echo $num1 5 $ num2=$num1+10 $ echo $num2 5+10
The expr statement must have white space around operators and operands. The expr statement automatically sends the value to standard output:
$ echo $num1 5 $ expr $num1 + 7 12 $ expr $num1+7 5+7 $ echo $num1 5
The following shows the need for properly quoting the multiplication operator.
$ expr $num1 * 2 expr: syntax error $ expr "$num1 * 2" 5 * 2 $ expr $num1 \* 2 10
When performing arithmetic, an operation result is stored in a variable. This is accomplished in the Bourne shell by placing the expr statement on the right side of a variable assignment statement:
$ echo $num1 5 $ num2=‘expr $num1 + 25‘ $ echo $num2 30 $ num3=‘expr $num1 + $num2‘ $ echo $num3 35 $ num4=‘expr $num1 \* $num2‘ $ echo $num4 150 $ num5=‘expr $num2 / $num1‘ $ echo $num5 6 $ num6=‘expr $num1 % 3‘ $ echo $num6 2
- Expressions (operations) within parentheses are evaluated first. Use a single pair of parentheses around an expression to force it to be evaluated first.
- Multiplication (*) and division (% and /) have greater precedence than addition (+) and subtraction (-).
- Arithmetic expressions are evaluated from left to right.
- When there is the slightest doubt, use parentheses to force the evaluation order.