Calculating with variables
Suppose
you run the following commands either in a shell script or by typing
in one command after another:
i=1
j=$i+1
echo $j
The output of echo is 1+1
, because
a normal variable assignment assigns a string to a variable.
Thus j
gets the string 1+1
.To evaluate an arithmetic expression, you
can enter:
let "variable=expression"
This
command line assigns the value of an expression to the given variable.
For example:
i=1
let "j=$i+1"
echo $j
Here j
is assigned the value of the expression
and the echo command displays the value 2
.You can also use let to change the value of a variable.
If you enter:
i=1
let "i=$i+1"
echo $i
the let command changes the
value of i
. The new value of i
is the old value
plus 1.A let command can have any of the standard arithmetic
expressions:
-A
- Negative
A
A*B
A
timesB
A/B
A
divided byB
A%B
- Remainder of
A
divided byB
A+B
A
plusB
A-B
A
minusB
- All unary minus operations are carried out;
- Then any
*
,/
, or%
operations (from left to right in the order they appear); - Then any additions or subtractions (from left to right in the order they appear).
let "i=5+2*3"
assigns 11 to i
, because the multiplication is done
first. You can use parentheses in the usual way to change the order
of operations. For example:
let "i=(5+2)*3"
assigns 21 to i
.
Note: let does not work with numbers that
have fractional parts. It works only with integers.