4- BASH Scripting – Using Math in scripts
Hello Linux-fanatics, this is my 4th tutorial in BASH Scripting series (other tutorials are HERE). In this tutorial we will be discussing about using mathematical operations in our scripts.
Learning to do Math in scripting is crucial feature as we must know how we manipulate numbers in BASH Scripting.
So, let’s get started ……
Firstly we should know various Arithmetic & Boolean operators that are used BASH scripting,
|+ –||Addition, subtration|
|++ —||Increment, decrement|
|* / %||Multiplication, division, remainder|
Logical and Boolean Operators
|<= >= < >||Less than or equal, greater than or equal, less than, greater than|
|== !=||Equal, not equal|
Now, let us see how we can use these in our scripts.
Using Arithmetic Operations in scripts
In order to perform arithmetic operations in scripts, we use “ $ [operation]”.
Same way we can use other operators also. Now, let me point out a limitation with using Arithmetic operations in BASH scripting. Let’s take an example,
Result of above script should be “2.5” but rather it shows only “2” . That is because BASH only supports integer arithmetic operations & doesn’t support floating point arithimetic, which is a huge limitation.
But this can be resolved i.e. we can do floating point arithmetic operations using bc command.
bc or bash calculator is a programming language that allows us to perform floating point arithmetic operations. We can either use bc directly by typing “bc ” in our BASH terminal or we can also use bc inside our scripts. Syntax for using bc in scripts is variable=$(echo “options; expression” | bc)
Here, “scale” shows number of decimal places upto which calculations are to be done. This script is a good example of how we can use bc to do floating point calculations in BASH.
This completes our tutorial on Mathematical operation in BASH scripting. I will be back with next tutorial soon. Feel free to send your comments/queries. ADIOS !!!