11.1 Arithmetic and Logic Operations

   

The let command performs both arithmetic and logic operations. The use of the let command is important because all loops depend on the control variable. The value of this control must be changed during the execution of the loop. Usually this value is incremented or decremented with the help of the let command. The loop structures also need logic operations, used for the testing value of the control variable. This is the second use of the let command. Like the test command, the let command also has explicit and implicit modes.

Explicit Mode let Command

In the explicit mode, the word let is used in the command line. Consider the following example of the use of the command.

 $  A=5  $  B=3  $  let "C=A+B"  $  echo $C  8 $ 

You created two new shell variables A and B and assigned these variables numeric values. Then you used the let command to sum these two values and assign the result to a third variable C . To display the value of this variable, you used the echo command. Like this arithmetic operation, you can also perform logic operations with the let command as shown in the following example.

 $  var1=5  $  var2=3  $  let "var1<var2"  $  echo $?  1 $  let "var1>var2"  $  echo $?  0 $ 

In this example, you compared two variables. The first comparison was not true, so the result code returned is 1. The second comparison is true and the result code is zero.

Implicit Mode let Command

You can replace the word let with double parentheses on each side of the expression. The above example, where you added two variables, can also be accomplished as follows .

 $  A=5  $  B=3  $  ((C=A+B))  $  echo $C  8 $ 

The let command can also perform complex operations like the one shown here.

 ((A=A+(3*B)/(A-1))) 

While evaluating the result of an expression, the usual arithmetic rules are applied. Parentheses can be used to alter the order of evaluation.

Table 11-1 lists the operators that can be used with the let command.

The first two operators are unary operators that need only one operand. All other operators are binary operators and need two operands. You will find many examples of the use of the let command in this chapter.

Table 11-1. Operators Used with the let Command
Operator Description
- Unary minus
! Unary negation (same value but with a negative sign)
= Assignment
+ Addition
- Subtraction
* Multiplication
/ Integer division
% Remainder
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
== Comparison for equality
!= Comparison for nonequality

   
Top


HP Certified
HP Certified: HP-UX System Administration
ISBN: 0130183741
EAN: 2147483647
Year: 2000
Pages: 390
Authors: Rafeeq Rehman

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net