Up: Programming the Shell
Previous: case: Selections
expr is used to perform arithmetic manipulations.
Five functions can be used:
Here is an example that uses all of them:
if test $# -lt 2 -o $# -gt 2
echo Must provide two and only two parameters.
SUM=`expr $1 + $2`
DIFF=`expr $1 - $2`
PRODUCT=`expr $1 "*" $2`
QUOTIENT=`expr $1 / $2`
REM=`expr $1 % $2`
TOTAL=`expr $SUM + $DIFF + $PRODUCT + $QUOTIENT + $REM`
echo The sum is $SUM.
echo The difference is $DIFF.
echo The product is $PRODUCT.
echo The quotient is $QUOTIENT.
echo The remainder is $REM.
echo The total sum of all these numbers is $TOTAL.
- The entire expr line is enclosed within back quotes.
Normally, the output of expr is the standard output.
Including the back quotes will assign the result to a variable.
- The * is between double quotes.
If it was not, the shell would interpret it as the wildcard character.
- expr is a shell feature found in both the Bourne and