10.3. Arithmetic

 <  Day Day Up  >  

There is not really a need to do math problems in a shell script, but sometimes arithmetic is necessary, for instance, to increment or decrement a loop counter. The C shell supports integer arithmetic only. The @ symbol is used to assign the results of calculations to numeric variables .

10.3.1 Arithmetic Operators

The following operators shown in Table 10.1 are used to perform integer arithmetic operations. They are the same operators as found in the C programming language. See Table 10.6 on page 538 for operator precedence. Also borrowed from the C language are shortcut assignment operators, shown in Table 10.2.

Example 10.5.
 1   %  @ sum = 4 + 6  echo $sum  10  2   %  @ sum++  echo $sum  11  3   %  @ sum += 3  echo $sum  14  4   %  @ sum--  echo $sum  13  5   % @  n = 3+4   @: Badly formed number  

Table 10.1. Integer Arithmetic Operators

Operator

Function

+

Addition

Subtraction

/

Division

*

Multiplication

%

Modulus

<<

Left shift

>>

Right shift


Table 10.6. Operator Precedence

Operator

Precedence

Meaning

( )

High

Low

Change precedence; group

~

Complement

!

Logical NOT, negation

* / %

Multiply, divide, modulo

+ “

Add, subtract

<< >>

Bitwise left and right shift

> >= < <=

Relational operators: greater than, less than

== !=

Equality: equal to, not equal to

=~ !~

Pattern matching: matches, does not match

&

Bitwise AND

^

Bitwise exclusive OR

Bitwise inclusive OR

&&

Logical AND

Logical OR


Table 10.2. Shortcut Operators

Operator

Example

Equivalent To

+=

@ num += 2

@ num = $num + 2

“=

@ num “= 4

@ num = $num “ 4

*=

@ num *= 3

@ num = $num * 3

/=

@ num /= 2

@ num = $num / 2

++

@ num++

@ num = $num + 1

“ “

@ num “ “

@ num = $num “ 1


EXPLANATION

  1. The variable sum is assigned the result of adding 4 and 6 . (The space after the @ is required.)

  2. The variable sum is incremented by 1 .

  3. The variable sum is incremented by 3 .

  4. The variable sum is decremented by 1 .

  5. Space

     <  Day Day Up  >  


UNIX Shells by Example
UNIX Shells by Example (4th Edition)
ISBN: 013147572X
EAN: 2147483647
Year: 2004
Pages: 454
Authors: Ellie Quigley

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