Operating System - HP-UX
1755595 Members
3859 Online
108836 Solutions
New Discussion юеВ

math command in shell script

 
SOLVED
Go to solution
Chushia
Frequent Advisor

math command in shell script

Is there a math command in shell script that can do percentage calculation ?
I have var1, var2, and would like to see the percentage of var1/var2.

Thanks
3 REPLIES 3
Peter Nikitka
Honored Contributor

Re: math command in shell script

Hi,

in ksh/posix shell:

typeset -i var1=56 var2=140
print $((var1*100/var2))

mfG nik
The Universe is a pretty big place, it's bigger than anything anyone has ever dreamed of before. So if it's just us, seems like an awful waste of space, right? Jodie Foster in "Contact"
James R. Ferguson
Acclaimed Contributor
Solution

Re: math command in shell script

Hi:

Depending on your goals (integer or real) there are several avenues to take.

Most shells only support integer arithmetic.

# X=100;Y=25;((Z=X/Y));echo $Z

If you want to incorporate real numbers, 'bc' provides a convenient vehicle. Choose the 'scale' to set the precision you want:

# X=1;Y=8;echo "scale=3\n $X/$Y"|bc

You can also leverage 'awk' and couple it with 'printf' to format output, including moving to a different number base:

# X=1;Y=8;echo "$X $Y"|awk '{printf "%.4f\n",$1/$2}'

# X=7;Y=8;echo "$X $Y"|awk '{printf "%4x\n",$1+$2}'

If you use the Korn93 shell, its 'typeset' allows a more direct approach to real numbers:

#!/usr/dt/bin/dtksh
typeset -F R1
typeset -F3 R2
typeset -E R3
let R1=1/8
echo $R1
let R2=1/8
echo $R2
let R3=1/8
echo $R3
exit 0

Regards!

...JRF...
Chushia
Frequent Advisor

Re: math command in shell script

Thank you all, it's beautiful!

I need precision, so I used bc.