|
|
The Korn shell can be told to perform arithmetic using variables. Because this facility is built into the shell calculations can be executed faster than by using expr, which is a separate program that must be forked and exec'ed (see fork(S) and exec(S)).
Although variables are normally treated as strings of characters, the command typeset -i can be used to specify that a variable must be treated as an integer, for example typeset -i MYVAR specifies that the variable MYVAR is an integer rather than a string. Following the typeset command, attempts to assign a non integer value to the variable will fail:
$To carry out arithmetic operations on variables or within a shell script, use the let command. let evaluates its arguments as simple arithmetic expressions. For example:typeset -i MYVAR
$MYVAR=56
$echo $MYVAR
56 $MYVAR=fred
ksh: fred: bad number $
$ let ans=$MYVAR+45
echo $ans
101
$
The expression above could also be written as follows:
$ echo $(($MYVAR+45))
101
$
Anything enclosed within $(( and )) is
interpreted by the Korn shell as being an arithmetic expression. It
is possible to include variables within such arithmetic expressions;
it is not necessary to prefix them with the usual dollar sign
although no error condition is caused if the dollar sign is used.
If you need to carry out calculations on floating point numbers, it is necessary to use the binary calculator, bc.