Friday, October 9, 2009

Linux - Bash Shell Scripting - Arithmetic and Relational Operators

The standard operators are available as shown in the table (note: there are more operators than those shown here; read the Bash man page for more information about the complete set of operators).

Within an expression, the normal precedence rules are applied; in the table precedence is from highest (unary minus, plus) to lowest (logical or).

- +
Unary minus, plus

! ~
Logical negation, bitwise negation

**
Exponentiation

* / %
Multiplication, division, remainder

+ -
Addition, Subtraction

<< >>
Left and right bitwise shifts

> < >= <= Greater than, less than, greater than or equal, less than or equal

== !=
Equal, not equal

&
Bitwise and

^
Bitwise exclusive or

|
Bitwise or

&&
Logical and

||
Logical or

Variables can be assigned integer values using normal assignment, or using let, e.g.,

x=33
let y=12
let z = 95 # error

The last statement will cause the shell script to fail; there should be no spaces to
the left and right of the = operator. Expressions are evaluated by enclosing them
in $[ … ], e.g.,

x=33
let y=12
z=$[x/y]
echo $z

The above displays 2 (note integer division is performed).

No comments:

Post a Comment