Trying to calculate radius and circle area in BASH

I am trying to write a basic script to calculate the radius and area of โ€‹โ€‹a circle, where PI = 3.14, and the circle is given. I am very new to scripting and I cannot figure it out.

#!/bin/bash
PI=3.14
CIRC=5
RAD=echo "((CIRC/2*PI))" | bc-l
printf "Radius: %.2f" $RAD
AREA=echo "((PI*RAD**2))" | bc-l
printf "Area: %.2f" $AREA

The sum of both equations is not stored in these variables, and I have no idea why. Hope someone can help explain.

+4
source share
2 answers

The below script will do this:

#!/bin/bash
pi=3.14
circ=5
rad=$( echo "scale=2;$circ / (2 * $pi)" | bc )
printf "Radius: %.2f\n" $rad
area=$( echo "scale=2;$pi * $rad * $rad" | bc )
printf "Area: %.2f\n" $area

Notes

+5
  • bc , printf. $(), . bash echo <<<:

    #!/bin/bash
    PI=3.14
    CIRC=5
    bc <<< "scale=2; r=$CIRC/(2*$PI)
            print "'"Radius: ", r, "\nArea: ", '"$PI"'*(r^2), "\n"'
    
  • POSIX, :

    #!/bin/sh
    PI=3.14
    CIRC=5
    bc << snip
          scale=2; r=$CIRC/(2*$PI)
          print "Radius: ", r, "\nArea: ", $PI * (r^2), "\n"
    snip
    
  • Pure bc:

    #!/usr/bin/bc -q
    pi=3.14; circ=5; scale=2; r=circ/(2*pi)
    print "Radius: ", r, "\nArea: ", pi*(r^2), "\n"
    quit
    
+4

Source: https://habr.com/ru/post/1648195/


All Articles