next up previous contents
Next: Korn shell options Up: Korn shell Previous: Korn shell background and

Korn shell arithmetic

Korn shell arithmetic is done using the let command:

$ let X=0
$ let X=X+1
$ print $X
Arithmetic operators have the same syntax as in C. The same function of the let command is achieved by ((....)) a preferred form as the brackets hide metacharacters.
Variables can be declared integer by one of the commands:

$ typeset -i i=12           #-i defaults to decimal base
$ integer j=44
$ integer k=4+3
Integer base can be specified in typeset as:

$ typeset -i2 X=5               # set binary base with -i2 or
$ typeset -i  X=2#101           # in the form base#value
Base definition can be used for data conversion. In the following example, a variable is set as base 10 integer (X=4095), than it is printed first in hexadecimal format and than in decimal. Format conversion is achieved using the typeset command. If the base is not 10, the base value followed by # is prefixed to the variable value, as shown in the following example:

$ typeset -i10 X; integer X=4095; echo $X
4095
$ typeset -i16 X; print $X
16#fff
$ typeset -i10 X=100; typeset -i2 Y; typeset -i16 Z; typeset -i8 O
$ Y=X; Z=X; O=X
$ print $X $Y $Z $O
100 2#1100100 16#64 8#144

When performing arithmetic operations use the form print - of the print statement to avoid problems with negative arguments.

Korn shell builtin $RANDOM can generate random numbers in the range 0:32767. At every call a new random value is generated. A start value can be set by initializing the RANDOM function with any integer. In this case for each seed a constant random value is generated.
Example:

print random no. $RANDOM
RANDOM=25
print random with seed 25 is: $RANDOM
typeset -i RN=$(print $RANDOM)
print  RN random no. is $RN
typeset -i RN=$(RANDOM=25; print $RANDOM)
print  RN random no. is $RN with seed = 25
Note the syntax used to assign the RANDOM value to a script variable:
typeset -i RN=$(print $RANDOM)
typeset -i RN=$(RANDOM=25; print $RANDOM)
The first form gives new values for each call:

$ typeset -i RN=$(print $RANDOM); $ print $RN
30033
$ typeset -i RN=$(print $RANDOM); print $RN
14827
$  typeset -i RN=$(print $RANDOM); print $RN
24321
while the second form produces a constant value for each seed:

$ typeset -i RN=$(RANDOM=25; print $RANDOM); print $RN
27741
$ typeset -i RN=$(RANDOM=25; print $RANDOM); print $RN
27741
$ typeset -i RN=$(RANDOM=35; print $RANDOM); print $RN
32284
$ typeset -i RN=$(RANDOM=35; print $RANDOM); print $RN
32284


next up previous contents
Next: Korn shell options Up: Korn shell Previous: Korn shell background and
Marisa Luvisetto
2001-02-05