We can use the bash built-in command let
for performing arithmetic operations. To get more information about let
, type the following:
$ help let
This should produce the following output of this command:
satish@backup:/home/satish$ help let
let: let arg [arg ...]
Evaluate arithmetic expressions.
Evaluate each ARG as an arithmetic expression. Evaluation is done in
fixed-width integers with no check for overflow, though division by 0
is trapped and flagged as an error. The following list of operators is
grouped into levels of equal-precedence operators. The levels are listed
in order of decreasing precedence.
id++, id-- variable post-increment, post-decrement
++id, --id variable pre-increment, pre-decrement
-, + unary minus, plus
!, ~ logical and bitwise negation
** exponentiation
*, /, % multiplication, division, remainder
+, - addition, subtraction
<<, >> left and right bitwise shifts
<=, >=, <, > comparison
==, != equality, inequality
& bitwise AND
^ bitwise XOR
| bitwise OR
& logical AND
|| logical OR
expr ? expr : expr
conditional operator
=, *=, /=, %=,
+=, -=, <<=, >>=,
&=, ^=, |= assignment
Shell variables are allowed as operands. The name of the variable
is replaced by its value (coerced to a fixed-width integer) within
an expression. The variable need not have its integer attribute
turned on to be used in an expression.
Operators are evaluated in order of precedence. Sub-expressions in
parentheses are evaluated first and may override the precedence
rules above.
Let’s start using the let
command:
$ value=6
$ let value=value+1
$ echo $value7
$ let "value=value+4"
$ echo $value11
$ let "value+=1"#above expression evaluates as value=value+1
$ echo $value12
A summary of operators available with the let
command follows:
- Operation:
Operator
- Unary minus:
-
- Unary plus:
+
- Logical NOT:
!
- Bitwise NOT (negation):
~
- Multiply:
*
- Divide:
/
- Remainder:
%
- Subtract:
-
- Add:
+
Prior to Bash 2.x, the following operators were not available:
- Bitwise left shift:
<<
- Bitwise right shift:
>>
- Equal to and not equal to:
==
,!=
- Comparison operators:
<=, >=, <, >
- Bitwise
AND
:&
- Bitwise
OR
:|
- Bitwise exclusive
OR
:^
- Logical
AND
:&
- Logical
OR
:||
- Assignment and shortcut assignment:
= *=/= %= -= += >>= <<= &= |= ^=