DOC HOME SITE MAP MAN PAGES GNU INFO SEARCH PRINT BOOK
 
Automating frequent tasks

Performing arithmetic on variables in the Korn shell

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:

   $ typeset -i MYVAR
   $ MYVAR=56
   $ echo $MYVAR
   56
   $ MYVAR=fred
   ksh: fred: bad number
   $
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:
   $ 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.


Next topic: Sending a message to a terminal
Previous topic: Performing arithmetic and comparing variables

© 2005 The SCO Group, Inc. All rights reserved.
SCO OpenServer Release 6.0.0 -- 03 June 2005