bash: Shell Arithmetic
1
1 6.5 Shell Arithmetic
1 ====================
1
1 The shell allows arithmetic expressions to be evaluated, as one of the
1 shell expansions or by using the '((' compound command, the 'let'
1 builtin, or the '-i' option to the 'declare' builtin.
1
1 Evaluation is done in fixed-width integers with no check for
1 overflow, though division by 0 is trapped and flagged as an error. The
1 operators and their precedence, associativity, and values are the same
1 as in the C language. The following list of operators is grouped into
1 levels of equal-precedence operators. The levels are listed in order of
1 decreasing precedence.
1
1 'ID++ ID--'
1 variable post-increment and post-decrement
1
1 '++ID --ID'
1 variable pre-increment and pre-decrement
1
1 '- +'
1 unary minus and plus
1
1 '! ~'
1 logical and bitwise negation
1
1 '**'
1 exponentiation
1
1 '* / %'
1 multiplication, division, remainder
1
1 '+ -'
1 addition, subtraction
1
1 '<< >>'
1 left and right bitwise shifts
1
1 '<= >= < >'
1 comparison
1
1 '== !='
1 equality and inequality
1
1 '&'
1 bitwise AND
1
1 '^'
1 bitwise exclusive OR
1
1 '|'
1 bitwise OR
1
1 '&&'
1 logical AND
1
1 '||'
1 logical OR
1
1 'expr ? expr : expr'
1 conditional operator
1
1 '= *= /= %= += -= <<= >>= &= ^= |='
1 assignment
1
1 'expr1 , expr2'
1 comma
1
1 Shell variables are allowed as operands; parameter expansion is
1 performed before the expression is evaluated. Within an expression,
1 shell variables may also be referenced by name without using the
1 parameter expansion syntax. A shell variable that is null or unset
1 evaluates to 0 when referenced by name without using the parameter
1 expansion syntax. The value of a variable is evaluated as an arithmetic
1 expression when it is referenced, or when a variable which has been
1 given the INTEGER attribute using 'declare -i' is assigned a value. A
1 null value evaluates to 0. A shell variable need not have its INTEGER
1 attribute turned on to be used in an expression.
1
1 Constants with a leading 0 are interpreted as octal numbers. A
1 leading '0x' or '0X' denotes hexadecimal. Otherwise, numbers take the
1 form [BASE'#']N, where the optional BASE is a decimal number between 2
1 and 64 representing the arithmetic base, and N is a number in that base.
1 If BASE'#' is omitted, then base 10 is used. When specifying N, the
1 digits greater than 9 are represented by the lowercase letters, the
1 uppercase letters, '@', and '_', in that order. If BASE is less than or
1 equal to 36, lowercase and uppercase letters may be used interchangeably
1 to represent numbers between 10 and 35.
1
1 Operators are evaluated in order of precedence. Sub-expressions in
1 parentheses are evaluated first and may override the precedence rules
1 above.
1