PreviousNext

Measuring and Counting with Expressions

The expr command offers flexible ways to express and use arithmetic functions in your scripts. Expressions are useful for things like comparing numeric information such as the number of elements in a list, setting thresholds for monitoring purposes, incrementing counters that control your script's execution, and producing statistical information.

A simple dcecp expression is a combination of an operator like + (add) or * (multiply) and some operands. The expr command takes one argument - the expression - so parentheses or braces may be needed if your expression has spaces. Use parentheses to control grouping in expressions. Expressions can also be nested. All of the following are valid expressions:

dcecp> expr {2 + 3}
5
dcecp> expr 2+3
5
dcecp> set x 24
24
dcecp> expr ($x-8)*2
32
dcecp> expr $x-(8*2)
8
dcecp> expr $x-8*2
8
dcecp>

Be careful using variables in expressions; variables like $x above must be numeric strings like 24, not non-numeric strings like 4*6.

The dcecp program normally treats numbers as integers in decimal format, but you can read numbers in octal and hexadecimal formats too. Precede a number with 0 for octal interpretation as in 0477. Precede a number with 0x for hexadecimal interpretation as in 0x9FF. You can also represent numbers in floating point using any of the forms specified by the ANSI C standard (with the exception of the f, F, l, and L suffixes).

The dcecp program also supports numerous mathematical functions in expressions such as cos, exp, log, tan, sin, and others, by invoking the C math library functions of the same name.

Here is a partial list of operators you can use with the expr command. The list order also denotes precedence. This means, for instance, that expr multiplies before adding (2+2*4 equals 10).

unary minus
~ bit-wise NOT
! logical NOT

* multiply
/ divide
% remainder

+ add
subtract

<< left shift
>> right shift

< boolean less than
<= boolean less than or equal
> boolean greater than
>= boolean greater than or equal

== boolean equal
!= not equal

& bitwise AND
^ bit-wise exclusive OR
| bit-wise OR

&& logical AND
|| logical OR

a?b:c if-then-else (as in C).