0

I have the below code which I'm trying to work out if a variable is lower than 95% of an average. My issue is that $avg its coming back with values that are not whole numbers 200.5 for example and bash doesn't like it. I'm not sure how to format my if in regards to the lower than.

servers=4
percentage=0.95
formula=$(($totalspace / $servers))
avg=$(echo $formula*$percentage | bc)

if [ $server1 -lt $avg ]
then

Thanks

1 Answer 1

3

You had the right idea shipping your calculation off to bc(1). Just carry that idea a little further and do the whole calculation there.

Things to keep in mind...

  1. bc will also return integer results by default, use scale = 4 or something
  2. bc can do the floating comparison too, relational operators return 0 or 1
  3. you might want to quote the calculation even though your * surrounded by digits is unlikely to be expanded, because the shell will try anyway.
Sign up to request clarification or add additional context in comments.

2 Comments

avg=$(echo "scale=4;$average*$percentage" | bc ) doesn't seem to help
Well, all by itself, of course not, because bash can't compare the floating point result. As I said, you need to do the comparison (and the earlier calculations) in bc also.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.