Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

What shell command to perform arithmetic with decimal values? 1

Status
Not open for further replies.

pho01

Programmer
Mar 17, 2003
218
US
I'm trying to calculate a tablespace free percent from a shell script.
Percent Free=Total Free/Total_Availble *100

p_free=`expr $total_free / $total_max_bytes`

This always returns 0, which I can't do further calculation.
per_free=`expr $p_free \* 100`

What command should I use instead? thanks
 
bc offers a good degree of control:

echo "scale=2; $p_free \* 100" | bc -l

scale=2 to set the number of decimal places.



 
The first one is the one that I have trouble with. I changed that to the following:

p_free=`scale=2; expr $total_free / $total_max_bytes`

p_free=`scale=2; expr $total_free / $total_max_bytes | bc -l`

they all return 0

What did I do wrong?

thanks,
 
Hi,
I always just add some zeros the the equation.....

per_free=`expr ${total_free}00 / $total_max_bytes`

Granted this TRUNCATED the percent to the lower whole number.

I think the note above is a neat way to do this using your variables.

echo "scale=2 ; $total_free / $total_max_bytes * 100" | bc -l
 


BC stands for Binary calculator.

you use it instead of EXPR. But it accepts input from STDIN no the command line so you have to TRICK it into accepting your input from the command line.

That is where the ECHO comes in.

change.

p_free=`scale=2; expr $total_free / $total_max_bytes | bc -l`

to

p_free=`echo "scale=2; $total_free / $total_max_bytes * 100" | bc -l`
 
Alternatively...

((p_free=100*total_free/total_max_bytes))
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top