Section 7.7. Arithmetic


[Page 265 (continued)]

7.7. Arithmetic

The let command allows you to perform arithmetic (Figure 7-15).

Figure 7-15. Description of the let shell command.

Shell Command: let expression

The let command performs double-precision integer arithmetic, and supports all of the basic math operators using the standard precedence rules. Here they are grouped in descending order of precedence:

OPERATOR

MEANING

-

unary minus

!

logical negation

* / %

multiplication, division, remainder

+ -

addition, subtraction

<= >= < >

relational operators

== !=

equality, inequality

=

assignment


All of the operators associate from left to right except for the assignment operator. Expressions may be placed between parentheses to modify the order of evaluation. The shell doesn't check for overflow, so beware! Operands may be integer constants or variables. When a variable is encountered, it is replaced by its value, which in turn may contain other variables. You may explicitly override the default base (10) of a constant by using the format base#number where base is a number between 2 and 36. You must not put spaces or tabs between the operands or operators. You must not place a $ in front of variables that are part of an expression.


Here are some examples:

$ let x = 2 + 2        ...expression contains spaces. ksh: =: syntax error   ...no spaces or tabs allowed! $ let x=2+2            ...OK. $ echo $x 4 
[Page 266]
$ let y=x*4 ...don't place $ before variables. $ echo $y 16 $ let x=2#100+2#100 ...add two numbers in base 2. $ echo $x 8 ...number is displayed in base 10. $ _


7.7.1. Preventing Metacharacter Interpretation

Unfortunately, the shell interprets several of the standard operators, such as <, >, and *, as metacharacters, so they must be quoted or preceded by a backslash ( \ ) to inhibit their special meaning. To avoid this inconvenience, there is an equivalent form of let that automatically treats all of the tokens as if they were surrounded by double quotes, and allows you to use spaces around tokens. The token sequence:

(( list ))


is equivalent to:

let " list "


Note that double quotes do not prevent the expansion of variables. I personally always use the ((..)) syntax instead of let. Here's an example:

$ (( x = 4 ))         ...spaces are OK. $ (( y = x * 4 )) $ echo $y 16 $ _ 


7.7.2. Testing Values

Arithmetic values may be used by decision-making control structures, such as an if statement:

$ (( x = 4 ))        ...assign x to 4. $ if (( x > 0 ))     ...OK to use in a control structure. > then >   echo x is positive > fi x is positive        ...output from control structure. $ _ 


For simple arithmetic tests, I recommend using ((..)) instead of test expressions.




Linux for Programmers and Users
Linux for Programmers and Users
ISBN: 0131857487
EAN: 2147483647
Year: 2007
Pages: 339

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