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

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:

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

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