Shell Variables   «Prev  Next»
Lesson 9Doing math with variables
ObjectiveEvaluate expressions using shell variables and operators.

Performing Math with Variables

Although using a shell script is not the best choice for doing most calculations with numbers, the expr command shown in the previous lesson can be used with many different operators to accomplish basic tasks.
The most common use of numbers in shell scripts is for counting iterations[1] through a loop or testing a value that is set by another program. These subjects are covered in later modules.

Using Arithmetic Operators

Basic arithmetic operations can be performed using the expr command to assign values to a variable. You must be certain that a variable contains only digits before attempting to perform a calculation on it. Suppose for the following examples that you have made the following assignments:

A=24
B=4

This table shows the basic operations that you can perform to assign a value to variable C. All of these are for integer arithmetic. No decimal places are saved in the results:

Using other Operators

The expr command supports many other operators, including some that can be used with string variables for operations like determining string length and locating a sub-string within a larger string. All of these require using an embedded expr command in your script statement (within back quotes as previously shown). The most common use of operators in scripts occurs when you use expr or another command as part of a test expression (described in an earlier module) within if/then statements. These are used to determine which actions a shell script should take.
When using more advanced shells such as bash, tcsh, ksh, or zsh, many additional operators are built into the shell (beyond what the expr command supports). These include various comparisons, bit-wise operators (for you C programmers) and additional mathematical operators.

Precedence in expressions

As you will recall from your algebra class, operators are acted on in a certain order. For example, multiplication is always done before addition. You can control the order (precedence) within an expression by using parentheses. The exact syntax for this varies depending on the shell that you are using. The following two examples show an expression evaluated in the Bourne shell with and without parentheses:

$ expr \( 24 + 6 \) \* 3
90
$ expr 24 + 6 \* 3
42

Using Numbers in Shell Variables - Quiz

Click on the Quiz link below to review what you have learned about using numbers in shell variables.
Using Numbers in Shell Variables - Quiz
One final variable topic which is array variables will be covered in the next lesson.

[1] Iteration: Executing a command or list of commands repeatedly, usually one time right after another, with a slightly different value each time through.