remedy remedy - 1 year ago 76
Bash Question

Trying to calculate radius and area of circle in BASH

I'm trying to write a basic script to calculate the radius and are are of a circle, PI=3.14, and the circumference is given. I am very very new to scripting, and I can't seem to figure this out.

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 are not being stored in those variables, and I have no idea why. I hope someone can help explain.

Answer Source

Below script would do it :

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


  1. See [ command substitution ].
  2. Never use full uppercase variables in your script as they are usually reserved for the system, check [ this ].
  3. scale with bc controls the precision, check [ this ].
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download