Kolo Zume
Kolo Zume

Reputation: 1

Addition/subtraktion/multiplikation of floats in bash with bc -l

I have some trouble with such an easy task...

Please find relevant code below:

loewdin_fuk=$(echo  $line_fukui|awk '{print $4}')

nbo_fuk=$(echo  $line_fukui|awk '{print $5}') 

echo "loewdin_fuk $loewdin_fuk nbo_fuk $nbo_fuk"

aver_fuk=$(($loewdin_fuk + $nbo_fuk))

\#aver_fuk=$(echo "scale=4; 0.5*($loewdin_fuk $nbo_fuk)" | bc -l)

The output is:

loewdin_fuk +0.1662 nbo_fuk +0.1865

./collectFukui.sh: line 151: +0.1662 + +0.1865: syntax error: invalid 

arithmetic operator (error token is ".1662 + +0.1865")

Using the command line:

aver_fuk=$(echo "scale=4; 0.5*($loewdin_fuk $nbo_fuk)" | bc -l) 

leads to following output:

loewdin_fuk +0.1662 nbo_fuk +0.1865

(standard_in) 1: syntax error

I don't get what's wrong... Thank you in advance!

Best,

Me

Upvotes: 0

Views: 92

Answers (1)

rici
rici

Reputation: 241701

The problem here is that bc does not consider + to be a unary operator. So +0.1662 +0.1865 is invalid syntax. (It would have worked ok if the first number were negative, because - is a unary operator.)

So if you want to use bc, you need to do something like:

aver_fuk=$(echo "scale=4; 0.5*(0$loewdin_fuk $nbo_fuk)" | bc -l)

Prepending 0 without a space will work whether or not $loewdin_fuk starts with a sign character. If you put a space in between, it would work with values with explicit sign characters, but fail on values without a sign.

Upvotes: 1

Related Questions