Bash Math: Difference between revisions
From charlesreid1
(Created page with "=Basic Math= Bash has some built-in functionality for really basic integer math, like addition, subtraction, multiplication, and division. ==Addition== <source lang="bash"> $ ...") |
No edit summary |
||
| Line 117: | Line 117: | ||
[[Category:Math Programs]] | [[Category:Math Programs]] | ||
[[Category:Programs]] | [[Category:Programs]] | ||
Revision as of 07:12, 28 May 2011
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
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.