It has the most basic mathematical computing capabilities in shell, such as expr and let. However, these operations can only process integer data. To calculate decimals, you must use the BC command extension. The following example shows how to determine the output parameter type and calculate its square.
- #! /Bin/sh
- # Filename: testbc
- Var = $1
- Dd = $ (echo $ var | BC 2>/dev/null)
- If ["$ Var "! = "$ Dd"] | ["$ Var" = ""]; then
- Echo "$ var isn't number! "
- Elif echo $ var | grep "/.">/dev/null 2>
- Then
- # Square = $ (echo "$ Var * $ Var" | BC)
- Square = $ (echo "$ Var * $ Var" | BC-l)
- Echo "$ VaR is a float number, square is: $ square"
- Else
- Square = $ (echo "$ Var * $ Var" | BC)
- Echo "$ VaR is a int number, square is: $ square"
- Fi
The script execution result is as follows:
$ Testbc aaa
AAA isn' t number!
$ Testbc 2
2 is a int number, square is: 4
$ Testbc 1.5
1.5 is a float number, square is: 2.25
If you want to process the accuracy of the calculation result, you can use scale to define the accuracy. You can do this:
$ Echo "scale = 3; 1.55*1.55" | BC-l
2.402
If the precision is not defined, the value of 1.55*1.55 is: 2.4025. Because we define the precision as 3, it displays the last three decimal places.
$ Echo "1.55*1.55" | BC-l
2.4025