Recent Changes - Search:

Basics

Languages

Tools

OS

Resources

PmWiki

pmwiki.org

edit SideBar

Arithmetic

Bash is a language where string concatenation takes priority over arithmetic.

Specifically, the result of x=2+2 is not 4. The value of x is literally the 2+2 character string, which is about as useful as "two plus two", except it can be evaluated. Similarly, doing x=$x+2 will store whatever was previously in x, with +2 appended to it, back into x. So if the previous value of x was 4, now it is 4+2.

Integer Arithmetic

In order to tell Bash that you want to actually do arithmetic, you need to surround the statement with double parentheses. ((statement)) should actually work.

For example:
x=2+2
echo $x
-> 2+2
((x=2+2))
echo $x
-> 4
x=$x+8
echo $x
-> 4+8
((x=$x+3))
echo $x
-> 15

Notice that, in the last statement, the original value of x being 4+8 was evaluated, and 4+8+3 gave the result of 15, instead of crashing when the number 3 could not be added to the '4+8' character string. This allows you to build formulas, or parse strings for certain characters which you know are mathematical expressions and then evaluate them.

This method of doing arithmetic meets its limits very fast, however, as it is strictly integer based. The formulas cannot contain decimal points, and the result of every operation will be rounded down.

For example:
((x=3/2))
echo $x
-> 1
((x=2*3/2))
echo $x
-> 3
((x=3/2*2))
echo $x
-> 2

where in the first formula 3/2 = 1.5 -> 1 which lead in the last formula to 3/2 = 1; 1*2 = 2. This shows that in integer arithmetic, multiplication and divisions are not commutative.

Floating Point Arithmetic

Edit - History - Print - Recent Changes - Search
Page last modified on August 06, 2015, at 05:04 PM