Performing arithmetic and comparing variables
It is sometimes useful to perform arithmetic, compare variables or
check for the existence of files using the shell. There are four
ways to do this:
-
Use the
test(C)
program to test variables for equivalence or existence.
-
Use the
expr(C)
expression evaluator to calculate on variables (as integer numbers)
or compare variables (as strings of text).
-
Use the
bc(C)
binary calculator (or another calculator, such as
dc(C)
or awk) to carry out more complex mathematical operations
(on decimals, fractions, and unusual bases).
-
Under the Korn shell only, use the ((..)) notation to evaluate
simple mathematical operations. This notation is equivalent to
let "...". Note that the ((..)) test is built into the
shell, and therefore executes faster.
test allows you to check if a named file exists and
possesses some property, or to test whether two strings are similar
or different. test is explained in detail in
``Different kinds of test''.
expr evaluates an expression and prints the result,
which can then be captured with backquotes. For example:
$ var=65
$ result=`expr $var \
5`
$ echo $result
325
$
Note the backslash in front of the ``
'' symbol.
is
short for multiplication in expr (and many other
programs), but the shell treats it as a filename wildcard character
and replaces it with a list of matching files unless it is escaped
(see
``Regular expressions'').
expr can also be used to manipulate variables containing text
(strings). A portion of a text string can be extracted; for example:
$ expr substr bobsleigh 4 6
sleigh
$
The substr expression returns a substring of its first
parameter (``bobsleigh'') starting at the character position
indicated by its second parameter (the fourth character: the character
is ``s''), of a length indicated by its third parameter (6 characters).
There are many additional options to expr. In general, you
can use expr to search a string for a substring, extract
substrings, compare strings, and provide information about a
string. It can also perform basic arithmetic on integer numbers,
but not on real numbers. For calculations that require decimals or
fractions, you should use a calculator, like bc. (See
``Putting everything together''
for an example of using bc within a shell script.)
Next topic:
Performing arithmetic on variables in the Korn shell
Previous topic:
Passing arguments to a shell script
© 2003 Caldera International, Inc. All rights reserved.
SCO OpenServer Release 5.0.7 -- 11 February 2003