As we have discussed on performing Arithmetic operations on our previous post, now we will look at the floating point operations in the shell script in this post.
You might want to look at :
Perform Arithmetic operations or mathematical calculations in Shell scripting - expr command
A huge limitation in the Bash shell is that it supports only integer arithmetic. There are several solutions to overcome this limitation. The famous solution is Bash Calculator.
Basics of BC(Bash Calculator):
The bash calculator is actually a programming language that allows you to enter floating point expressions at the command line and then interprets the expressions, calculates and then returns the result. The Bash calculator recognizes the following:
- Numbers (both integer and floating point)
Variables (both simple variables and arrays)
Comments (lines starting with a pound sign or the C language /* */ pair
Programming statements (such as if‐then statements)
As you can see from the above example, each time you enter the expression, you get the result immediately. To exit the BC you need to type quit.
Floating point decimal is controlled by a variable called "scale". Using this variable we can specify no. of decimal places that we would like to see in our result.
The default value of the scale is zero. As you can see from the above example, the Bash calculator returns the answer with zero decimal places. After setting the scale to 4, it displays the result with 4 decimal places.
The -q parameter suppresses the lengthy welcome banner of the Bash Calculator. In addition to the normal numbers, the bash calculator also understands the variables.
Once a variable is defined you can use the variable throughout the Bash calculator session. The "print" statement is used to print the variables and numbers.
Using BC in the scripts:
We can use the BC in our script in two ways.
1) Using the back tick character to run the "bc" command and assign the result to the variable as shown below.
variable=‘echo “options; expression” | bc’
Below is a sample script which illustrates the above usage.
This method will be useful for small calculations. For the calculations which involves more complex expressions, the next method will be useful.
2) Using the inline input redirection, you can perform calculations which involves more numbers. The syntax of this method would be,
variable=‘bc << EOF
The EOF text string indicates the beginning and end of the inline redirection data. Remember that the backtick characters are still needed to assign the output of the bc command to the variable.
Below is an example script to show the usage of input redirection in BC.
Note: The variables declared inside the Bash calculator is valid only inside the BC and can't be used in the shell script.