2

I'm trying to do this in Ubuntu virtualbox with a shell text:

#!/bin/bash

n1=3.5
n2=3.6
n3=3.7
n=3
let promedio=n1+n2+n3/3
echo $promedio

is about the Average student grade. But then the terminal shows the error:

line 7: let: 3.5: syntax error: invalid arithmetic operator (error token is ".5")

Why? I can't do the + with numbers. What can I do?

I was reading about BC command but I don't know where it goes.

EDIT: I tried adding | BC at the end but is the same error. Also I tried looking at a post about this but they use something different I really don't understand because I'm really new with Ubuntu. They use the $echo or something like that but the code I'm using is different.

2
  • @Melebius VTC + Please upvote the bc answer to the linked duplicate question that you found useful. I upvoted this answer because I thought it was more useful than the other one.
    – karel
    Nov 13, 2019 at 7:49
  • @karel I guess OP wants to use the calculation in a shell script, so I find the echo | bc form better. It’s covered by the most upvoted steeldriver’s answer. But you are right… I’ve upvoted it right now.
    – Melebius
    Nov 13, 2019 at 7:58

1 Answer 1

4

There is no floating point arithmetic operation in bash. So, you can use BC to calculate it:

#!/bin/bash

n1=3.5
n2=3.6
n3=3.7
promedio=`echo $n1 + $n2+ $n3/3 | bc`
echo $promedio   # 3.5 + 3.6 + 1 = 8.1 **This might be not what you want**

BC is a simple command line calculator.

BTW, echo <expression> | bc command will send the calculation of the expression that is obtained using BC to bash.

A little explanation:

  • So, by encapsulating with two `, you are telling that the value promedio is a result that is obtained by command. (In other words, it is called command substitution, see here for more information)

  • By using echo you are saying that the result will be the output of some calculation that is obtained by BC.

  • And there is a logical flaw in these commands, if you use bc like this, it will divide in terms of integer, (3.7/3 = 1), so you should use bc -l command to (3.7/3 = 1.2333...) calculate precisely.

And to divide the sum of these 3 numbers, you should properly do parenthesis:

#!/bin/bash

n1=3.5
n2=3.6
n3=3.7
promedio=`echo "($n1 + $n2+ $n3)/3" | bc -l`
echo $promedio     # (3.5 + 3.6 + 3.7)/3 = 3.60000...
8
  • Thank you! It worked. Hey mind if I ask you, what does the " ` " little dot means in the bc and echo? I'm trying to learn all about this. Thanks
    – LeoTwix
    Nov 13, 2019 at 7:54
  • 1
    I think the expression is meant to be: ($n1 + $n2 + $n3) / 3
    – FedKad
    Nov 13, 2019 at 7:55
  • @LeoTwix, I will edit the answer.
    – Olimjon
    Nov 13, 2019 at 7:55
  • @Olimjon Okay, I will check.
    – LeoTwix
    Nov 13, 2019 at 7:56
  • 1
    By the way, $( ) should be preferred for command substitution.
    – Melebius
    Nov 13, 2019 at 8:01

Not the answer you're looking for? Browse other questions tagged .