zsh - Arithmetic Evaluation

Go to the first, previous, next, last section, table of contents.

# Arithmetic Evaluation

An ability to perform integer arithmetic is provided with the builtin `let`. Evaluations are performed using long arithmetic. A leading `0x` or `0X` denotes hexadecimal. Otherwise, numbers are of the form `[base#]n` where base is a decimal number between two and thirty-six representing the arithmetic base and n is a number in that base (for example, `16#ff` is 255 in hexadecimal). If base is omitted then base 10 is used. For backwards compatibility the form `[16]ff` is also accepted.

An arithmetic expression uses nearly the same syntax, precedence, and associativity of expressions in C. The following operators are supported (listed in decreasing order of precedence):

`+ - ! ~ ++ --`
  Unary plus/minus, logical NOT, complement, {pre,post}{in,de}crement
`<< >>`
  Bitwise shift left, right.
`&`
  Bitwise AND
`^`
  Bitwise XOR
`|`
  Bitwise OR
`**`
  Exponentiation
`* / %`
  Multiplication, division, modulus (remainder)
`+ -`
  Addition, subtraction
`< > <= >=`
  Comparison
`== !=`
  Equality and inequality
`&&`
  Logical AND
`|| ^^`
  Logical OR, XOR
`? :`
  Ternary operator
`= += -= *= /= %= &= ^= |= <<= >>= &&= ||= ^^= **=`
  Assignment
`,`
  Comma operator

The operators `&&`, `||`, `&&=`, and `||=` are short-circuiting, and only one of the latter two expressions in a ternary operator is evaluated. Note the precedence of the bitwise AND, OR, and XOR operators.

An expression of the form `#\x` where `x` is any character gives the ASCII value of this character. An expression of the form `#foo` gives the ASCII value of the first character of the value of the parameter `foo`.

Named parameters and subscripted arrays can be referenced by name within an arithmetic expression without using the parameter substitution syntax.

An internal integer representation of a named parameter can be specified with the `integer` builtin. Arithmetic evaluation is performed on the value of each assignment to a named parameter declared integer in this manner.

Since many of the arithmetic operators require quoting, an alternative form of the `let` command is provided. For any command which begins with a `((`, all the characters until a matching `))` are treated as a quoted expression. More precisely, `(( ... ))` is equivalent to `let "..."`.

Go to the first, previous, next, last section, table of contents.