How-to: Arithmetic expressions

The shell allows arithmetic expressions to be evaluated, as one of the shell expansions or by the let builtin.

Evaluation is done in long integers with no check for overflow, though division by 0 is trapped and flagged as an error. The operators and their precedence and associativity are the same as in the C language.

The following list of operators is grouped into levels of equal-precedence operators. The levels are listed in order of decreasing precedence.

Operator Meaning
* Multiplication
/ Division
% Remainder
+ Addition (also Unary plus)
- Subtraction (also Unary minus)
<< Left bitwise shift
>> Right bitwise shift
++id Variable pre-increment.
Increments the value of a variable before using it in an expression.
--id Variable pre-decrement
id++ Variable post-increment.
Increments the value of variable after executing the expression completely.
id-- Variable post-decrement.
! Logical negation
~ bitwise negation
** Exponentiation
<=
>=
< >
Comparison
== Equality
!= Inequality
& Bitwise AND
^ Bitwise exclusive OR
| Bitwise OR
&& Logical AND
|| Logical OR
expr ? expr : expr Conditional evaluation
=
*= /
=
%=
+=
-=
<<=
>>=
&=
^=
|=
Assignment
expr1 , expr2 Comma

Shell variables are allowed as operands; parameter expansion is performed before the expression is evaluated. Within an expression, shell variables can also be referenced by name without using the parameter expansion syntax. The value of a variable is evaluated as an arithmetic expression when it is referenced. A shell variable need not have its integer attribute turned on to be used in an expression.

Constants with a leading 0 are interpreted as octal numbers.
A leading '0x' or '0X' denotes hexadecimal.
Otherwise, numbers take the form [base#]n, where base is a decimal number between 2 and 64 representing the arithmetic base, and n is a number in that base.

If base# is omitted, then base 10 is used. The digits greater than 9 are represented by the lowercase letters, the uppercase letters, '_', and '@', in that order. If base is less than or equal to 36, lowercase and uppercase letters can be used interchangably to represent numbers between 10 and 35.

Operators are evaluated in order of precedence. Sub-expressions in parentheses are evaluated first and can override the precedence rules above.

Related Linux commands

Bash Syntax
NIST Digital Library of Mathematical Functions
Windows equivalent command: SET /A - Display, set, or remove Windows environment variables.

(追記) (追記ここまで)
Copyright © 1999-2026 SS64.com
Some rights reserved

AltStyle によって変換されたページ (->オリジナル) /