Working out percentage in shell script

Hi All,
I currently have a shell script which is pulling multiple counters from various sources. Due to the counters being cumulative counters I've got some code to work out the delta from the last reading and current which is working fine.

The problem i have now is being able to work out the success rate as a percentage.

Normally I would just take success and divide by attempts then multiply this by 100 which would give my success rate at a percentage (i'd like it to 2 decimal places).

How can this be done in a shell script ?

Any help is apprecaited as always.

Thanks

Here are some options to do so:

shell - How to do integer & float calculations, in bash or other languages/frameworks? - Unix & Linux Stack Exchange

What am i doing wrong ?

sum1=$((add1 + add2))
echo "Success = $sum1"
sum2=$((add3 - add4))
echo "Attempts = $sum2"
final="scale=4; ($sum1 / $sum2 ) * 100" | bc
echo " Success rate = $final"

No percentage is worked out, it only is printing Sum1 and Sum2 values.

Success = 7513
Attempts - custom = 9150
Success Rate = 

what i'm expecting is the below output.

Success = 7513
Attempts - custom = 9150
Success Rate = 82.10

You need to use "command substitution" (c.f. man bash ). Try

final=$( echo "scale=4; ($sum1 / $sum2 ) * 100" | bc)

or, if you have a recent shell, a "here string"

 bc <<< "scale=4; ($sum1 / $sum2 ) * 100"
1 Like

Thanks RudiC, Do you know how i can round it up ?

This should help you after reading the thread...

Round it up? Means WHAT? How about scale=2 ?

Note that if you're willing to use a 1993 or later Korn shell instead of bash, it is happy to perform arithmetic substitutions in floating point:

$ sum1=7513
$ sum2=9150
$ echo $((sum1 * 100./sum2))
82.1092896174863388
$ printf '%.2f\n' $((sum1 * 100./sum2))
82.11
$ 

Note that if the decimal point had been omitted in the calculation marked above in red, ksh would have used integer arithmetic instead of floating point.

IMPORTANT!

If you are using a DEFAULT CygWin(64) install then you only have one choice for floating point maths, awk , all other commands and languages do not exist...

The current CygWin(64) shell is bash Version 4.3.4.
Example:-

awk 'BEGIN { printf "%.2f\n", ( 1.517 / 0.713 ) }'

Rounds up to the second decimal place.