The Korn shell or POSIX shell let regular built-in command enables you to perform integer arithmetic. Constants are of the form [Base]Number. The Base parameter is a decimal number between 2 and 36 inclusive, representing the arithmetic base. The Number parameter is a number in that base. If you omit the Base parameter, the shell uses a base of 10.
Arithmetic expressions use the same syntax, precedence, and associativity of expression as the C language. All of the integral operators, other than ++ (double plus), -- (dash), ?: (question mark, colon) and , (comma), are supported. The following Korn Shell Arithmetic Operators table lists valid Korn shell or POSIX shell operators in decreasing order of precedence:
Korn Shell Arithmetic Operators | |
Operator | Definition |
- | Unary minus |
! | Logical negation |
~ | Bitwise negation |
* | Multiplication |
/ | Division |
% | Remainder |
+ | Addition |
- | Subtraction |
<<, >> | Left shift, right shift |
<=,>=, <>, ==, != | Comparison |
& | Bitwise AND |
^ | Bitwise exclusive OR |
| | Bitwise OR |
&& | Logical AND |
|| | Logical OR |
= *=, /=, &= +=, -=, <<=, > >=, &=, ^=, |= | Assignment |
Many arithmetic operators, such as *, &, <, and >, have special meaning to the Korn shell or POSIX shell. These characters must be quoted. For example, to multiply the current value of y by 5 and reassign the new value to y, use the expression:
let "y = y * 5"
Enclosing the expression in quotes removes the special meaning of the * (asterisk) character.
You can group operations inside let command expressions to force grouping. For example, in the expression:
let "z = q * (z - 10)"
the command multiplies q by the reduced value of z.
The Korn shell or POSIX shell includes an alternative form of the let command if only a single expression is to be evaluated. The shell treats commands enclosed in (( )) (double left parentheses, double right parentheses) as quoted expressions. Therefore, the expression:
((x = x / 3))
let "x = x / 3"
Named parameters are referenced by name within an arithmetic expression without using the parameter substitution syntax. When a named parameter is referenced, its value is evaluated as an arithmetic expression.
Specify an internal integer representation of a named parameter with the -i flag of the typeset special built-in command. Using the -i flag, arithmetic evaluation is performed on the value of each assignment to a named parameter. If you do not specify an arithmetic base, the first assignment to the parameter determines the arithmetic base. This base is used when parameter substitution occurs.