Bash Math
From charlesreid1
Contents
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).
You can find the bc man page here: http://unixhelp.ed.ac.uk/CGI/man-cgi?bc+1
The gist of how you script mathematical operations with bc is, you echo the operation you want to perform, and you pipe it to bc. bc then performs the calculation and spits out the result.
For example:
$ echo "25.7 + 90.1384" | bc 115.8384 $ echo "25.7 >= 90.1384" | bc 0 $ echo "25.7 <= 90.1384" | bc 1 $ echo "sqrt(85)" | bc 9 $ echo "sqrt(85.0)" | bc 9.2 $ echo "sqrt(85.000000)" | bc 9.219544
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.
GNU/Linux/Unix the concrete that makes the foundations of the internet.
Compiling Software · Upgrading Software Category:Build Tools · Make · Cmake · Gdb Bash Bash · Bash/Quick (Quick Reference) · Bash Math Text Editors Text Manipulation Command Line Utilities Aptitude · Diff · Make · Patch · Subversion · Xargs Security SSH (Secure Shell) · Gpg (Gnu Privacy Guard) · Category:Security Networking Linux/SSH · Linux/Networking · Linux/File Server Web Servers
|
Scientific Computing Topics in scientific computing.
Numerical Software: Lapack · Sundials · Matlab · Octave · FFTW Petsc · Example Petsc Makefile · Trilinos · Hypre · Ginac · Gnuplot
Python: Numpy · Scipy · Pandas · Matplotlib · Python Sundials · Py4Sci Scikit-learn: Sklearn · Skimage
|