Section 6.6. Arithmetic Expressions


6.6. Arithmetic Expressions

The let command performs arithmetic. ksh88 and Bash are restricted to integer arithmetic. ksh93 can do floating-point arithmetic as well. Both shells provide a way to substitute arithmetic values (for use as command arguments or in variables); base conversion is also possible.

Expression

Meaning

$(( expr ))

Use the value of the enclosed arithmetic expression.

B#n

Interpret integer n in numeric base B. For example, 8#100 specifies the octal equivalent of decimal 64.


6.6.1. Operators

The shells use arithmetic operators from the C programming language; the following table listing is in decreasing order of precedence. ksh88 does not support the ++, --, unary +, ?:, comma or ** operators. Early versions of ksh93 do not have **.

Operator

Operator

++ --

Auto-increment and auto-decrement, both prefix and postfix.

+ - ! ~

Unary plus and minus, logical negation and binary inversion (one's complement).

**

Exponentiation.[a]

* / %

Multiplication; division; modulus (remainder).

+ -

Addition; subtraction.

<< >>

Bitwise left shift; bitwise right shift.

< <= > >=

Less than; less than or equal to; greater than; greater than or equal to.

== !=

Equality; inequality (both evaluated left to right).

&

Bitwise AND.

^

Bitwise exclusive OR.

|

Bitwise OR.

&&

Logical AND (short-circuit).

||

Logical OR (short-circuit).

?:

Inline conditional evaluation.

= += -=

Assignment.

*= /= %=

 

< <= > >=

 

&= ^= |=

 

,

Sequential expression evaluation.


[a] In ksh93, the ** operator is right associative. In bash versions prior to 3.1, it is left associative. It will be changed to right associative starting with version 3.1.

6.6.2. Built-in Mathematical Functions (ksh93 only)

ksh93 provides access to the standard set of mathematical functions. They are called using C function call syntax.

Name

Function

Name

Function

abs

Absolute value

hypot

Euclidean distance

acos

Arc cosine

int

Integer part of floating-point number

asin

Arc sine

log

Natural logarithm

atan

Arc tangent

pow

Exponentiation (xy)

atan2

Arc tangent of two variables

sin

Sine

cos

Cosine

sinh

Hyperbolic sine

cosh

Hyperbolic cosine

sqrt

Square root

exp

Exponential (ex)

tan

Tangent

fmod

Floating-point remainder

tanh

Hyperbolic tangent


6.6.3. Examples

See the let command for more information and examples:

     let "count=0" "i = i + 1"     Assign i and count     let "num % 2"     Test for an even number     (( percent >= 0 && percent <= 100 ))      Test the range of a value 



Linux in a Nutshell
Linux in a Nutshell
ISBN: 0596154488
EAN: 2147483647
Year: 2004
Pages: 147

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