0

I am a beginner of bash shell scripting. I am using bc for float type data calculation, but I got the following error. I have tried to search this on-line, but wasn't able to solve this. My simplified code and error are attached below.

aa=1270000000.000000
bb=14000000
cc=-5245200.55453439363590374313
dd=4666666.66666666666666666666
ee=$(echo "$aa-$bb/2-$cc+2.5*$dd" | bc -l)

(standard_in) 1: syntax error

The strange thing is that, the following code seems work.

aa=1.222
bb=2
cc=3.999
dd=4.222222
ee=$(echo "$aa-$bb/2-$cc+2.5*$dd" | bc -l)

This is weird, but I don't know how this happen. Does anyone have any idea about this? Thanks in advance.

1
  • I've always liked polish notation. ee=$(dc -e "$aa $bb 2 / - $cc - 2.5 $dd * + p"). Commented Sep 11, 2017 at 18:45

2 Answers 2

2

bc's parser treats adjacent negative signs as the decrement operator; 3--3 is not the same as 3 - -3 or 3-(-3). You need to adjust the argument to echo accordingly, to accomodate a value of cc that begins with a -.

ee=$(echo "$aa-$bb/2-($cc)+2.5*$dd" | bc -l)

or

ee=$(echo "$aa - $bb / 2 - $cc + 2.5 * $dd" | bc -l)
Sign up to request clarification or add additional context in comments.

Comments

0

bc needs spaces between operators.

aa=1270000000.000000
bb=14000000
cc=-5245200.55453439363590374313
dd=4666666.66666666666666666666
ee=$(echo "$aa - $bb / 2 - $cc + 2.5 * $dd" | bc -l)

1 Comment

This is not generally correct. It only needs spaces to tell 1--2 apart from 1-(-2).

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.