In Bash shell, we can only perform integer arithmetic. If we want to perform arithmetic involving a floating point or fractional values, then we will need to use various other utilities, such as awk
, bc
, and similar.
Let's see an example of using the utility called bc
:
$ echo "scale=2; 15 / 2" | bc 7.50
For using the bc
utility, we need to configure a scale parameter. Scale is the number of significant digits to the right of the decimal point. We have told the bc
utility to calculate 15 / 2
, and then display the result with the scale of 2
.
Or:
$ bc ((83.12 + 32.13) * 37.3) 4298.82
Many things can be done with the bc
utility, such as all types of arithmetic operations including binary and unary operations; it has many defined mathematical functions. It has its own programming syntax.
You can get more information about the utility bc
at http://www.gnu.org/software/bc/.
Let's look at using awk
for a floating-point arithmetic:
$ result=`awk -v a=3.1 -v b=5.2 'BEGIN{printf "%.2f ",a*b}'` $ echo $result 16.12
You will be learning more about the awk
programming in the coming chapters. Therefore, we will not get into a detailed discussion of awk
in this session.
Let's write few more Shell scripts using arithmetic programming skill in shell, which we have learned so far.
Let's write the Bash Shell script arithmetic_08.sh
to find whether an input integer is even or odd:
#!/bin/bash echo "Please enter a value" read x y=`expr $x%2` if test $y -eq 0 then echo "Entered number is even" else echo "Entered number is odd" fi
Let's test the program:
$ chmod +x arithmetic_08.sh $ ./arithmetic_08.sh
Output:
$ ./hello.sh "Enter a number" 5 "Number is odd" $ ./hello.sh "Enter a number" 6 "Number is even"
Let's write the script arithmetic_09.sh
to find the length of an input string:
#!/bin/bash echo "Please Enter the String:" read str len=`echo $str | wc -c` let len=len-1 echo "length of string = $len"
Let's test the script:
$ chmod +x arithmetic_09.sh $ ./arithmetic_09.sh
Output:
Enter String: Hello World length of string = 11
Let's write a script to calculate the area and circumference of a rectangle and circle.
Write the Shell script arithmetic_10.sh
as follows:
#!/bin/bash echo "Please enter the length, width and radius" read length width radius areaRectangle=`expr $length * $width ` temp=`expr $length + $width ` perimeterRect=`expr 2 * $temp` areaCircle=`echo 3.14 * $radius * $radius | bc` circumferenceCircle=`echo 2 * 3.14 * $radius | bc` echo "Area of rectangle = $areaRectangle" echo "Perimeter of Rectangle = $perimeterRect." echo "Area of circle = $areaCircle." echo "Circumference of circle = $circumferenceCircle" echo
$ chmod +x arithmetic_10.sh $ ./arithmetic_10.sh
Output:
Enter the length, width and radius 5 10 5 Area of rectangle = 50 Perimeter of Rectangle = 30 Area of circle = 78.50 Circumference of circle = 31.40