next up previous contents
Next: Subroutines Up: Programming the Shell Previous: case: Selections

expr: Doing Arithmetic

expr is used to perform arithmetic manipulations. Five functions can be used:

+
addition.
-
subtraction.
*
multiplication.
/
division.
%
remainder.

Here is an example that uses all of them:

    #!/bin/sh
    if test $# -lt 2 -o $# -gt 2
    then
        echo Must provide two and only two parameters.
        exit 1
    fi
    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.
    exit 0

NOTES:



Claude Cantin
Sun Sep 1 02:02:26 EDT 2002