This topic is about Linux Admin – Basic Math Operations.
Bash does integer math using the common operators for addition, subtraction, multiplication, and division.
+ | Addition |
– | Subtraction |
* | Multiplication |
/ | division |
% | Modulus |
<< | Increment |
— | Decrement |
When performing math operations, it is necessary to use the format of $((math formula))
Note − When using $() BASH, it will execute a command. echo $(ls) will print the output of ls to the terminal. Adding an additional nest () will let BASH know the math operations to be performed.
In the following code, we use the pre-increment operator to increment as it is printed to the terminal.
#!/bin/bash for i in `seq 0 10`; do echo $((++i)) done
Following will be the output.
1 2 3 4 5 6 7 8 9 10 11
More basic math operations −
#!/bin/bash echo $((2+1)) echo $((2-1)) echo $((2*1)) echo $((2/1)) echo $((2%1))
Following will be the output.
3 1 2 2 0
Performing math operations on integers is pretty simple in BASH. The developer just needs to remember integer operations are always performed in $(()), telling BASH it is math.
For floating point numbers, we want to use the bc command −
#!/bin/bash echo 1.1+2.3 | bc
Following will be the output.
3.4
bc can get pretty complex but at the same time is a very powerful command-line calculator.
Here is the man page for bc −
bc is a language that supports arbitrary precision numbers with interactive execution of statements. There are some similarities in the syntax to the C programming language. A standard math library is available by the command line option. If requested, the math library is defined before processing any files. bc starts by processing the code from all the files listed on the command line in the order listed. After all files have been processed, bc reads from the standard input. The entire code is executed as it is read. (If a file contains a command to halt the processor, bc will never read from the standard input.)
This version of bc contains several extensions beyond traditional bc implementations and the POSIX draft standard. Command line options can cause these extensions to print a warning or to be rejected. This document describes the language accepted by this processor. Extensions will be identified as such.
Just remember, using bc is best with floating point operations and the shell can handle integer math. You will need to pass your operands to bc. Finally, the scale parameter specifies the precision of the solution.
#!/bin/bash echo 'scale = 3; 1.19*2.3' | bc -q
Following will be the output.
2.737
Pingback: Linux Admin - Read and Write to Files - Adglob Infosystem Pvt Ltd