From charlesreid1

Basic Math

Bash has some built-in functionality for really basic integer math, like addition, subtraction, multiplication, and division.

Addition

$ sum=$((2+2))  &&   echo $sum
4

$ sum=$((sum+10))  &&   echo $sum
14

Subtraction

$ diff=$((100-50))   &&   echo $diff
50

$ diff=$((diff-25))   &&   echo $diff
25

Multiplication

$ prod=$((2*8))    &&   echo $prod
16

$ a=9; b=3; prod=$((a*b))    &&   echo $prod
27

Division

$ a=14; b=2; div=$((a/b))   &&   echo $div
7

Remainder

$ a=10; b=4; z=$((a%b))   &&   echo $z
2

Exponentiation

$ z=5   &&   echo $z
5

$ zz=$((z**2))   &&   echo $zz
25


Complex Math

To do anything more complex than basic integer math, you have to use the program bc (bash calculator).

Stump.gif This section is a stub.

A team of expertly-trained librarian ninjas has been dispatched to research this topic, finish this section, and assassinate all eyewitnesses who contradict their account.

They should be done pretty soon.

Template:Stub

Category:Stubs

Operators

You can use the increment and decrement operators ++ and -- as follow:

Increment++

The increment operator can be used as either a prefix or postfix operator, i.e. as ++i or i++. Example:

$ z=1   &&   echo $z
1

$ ((++z))   &&   echo $z
2

$ ((++z))   &&   echo $z
3

$ ((++z))   &&   echo $z
4

This can be used in bash for loops as follows:

for ((i=1; i <=$NUM ; i++)); do
    echo $i
done

Decrement--

Like the increment operator, this can be a prefix or postfix operator, i.e. --i or i--:

$ z=1   &&   echo $z
1

$ ((--z))   &&   echo $z

$ ((--z))   &&   echo $z
-1

$ ((--z))   &&   echo $z
-2

$ ((--z))   &&   echo $z
-3

Notice that echo $z doesn't print anything if z=0.