|
|
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:
expr evaluates an expression and prints the result, which can then be captured with backquotes. For example:
$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'').var=65
$result=`expr $var \ 5`
$echo $result
325 $
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.)