Linux Help
guides forums blogs
Home Desktops Distributions ISO Images Logos Newbies Reviews Software Support & Resources Linuxhelp Wiki

Welcome Guest ( Log In | Register )

Advanced DNS Management
New ZoneEdit. New Managment.


Sign Up Now
> Negative Number Subtraction in Arrays
post Feb 22 2016, 12:41 PM
Post #1

Whats this Lie-nix Thing?

Group: Members
Posts: 15
Joined: 22-February 16
Member No.: 19,047


I am having a dickens of a time working out how to do subtraction of two negative numbers in an array. My script is as below; I put hashmarks for commented out regions of failed alternatives I tried to make this work. I assure all that the arrays shear1 and shear2 are well-defined when I checked it with various print statements.

while [ $i -lt 8 ]
#shear_sum[i]='expr ${shear1[i]} + ${shear2[i]}'
#shear_sum[i]=$(expr ${shear1[i]} + ${shear2[i]})
#shear_sum[i]=$(${shear1[i]}+${shear2[i]}| bc)
shear_sum[i]=$((${shear1[i]} + ${shear2[i]}))
echo "${shear_sum[@]}"

Upon execution:

./shear_stats: line 39: -0.24 + -0.09: syntax error: invalid arithmetic operator (error token is ".24 + -0.09")

Which is to say, it does not recognize the negative number (-0.24).

If I instead use the 3rd commented line, and comment out the 4rth, I get

./shear_stats: line 40: -0.24+-0.09: command not found
./shear_stats: line 40: -0.55+-0.14: command not found
./shear_stats: line 40: -0.48+-0.16: command not found
./shear_stats: line 40: -0.65+-0.26: command not found
./shear_stats: line 40: 0.48+1.06: command not found
./shear_stats: line 40: 0.39+0.31: command not found
./shear_stats: line 40: 0.60+0.25: command not found
./shear_stats: line 40: -0.54+-0.30: command not found

In this case, the negative number is recognized, but the binary operation is not understood despite the use of bc. I tried playing with the spacing of the negative signs around the addition sign, but changing this didn't do anything.

Can anyone advise me?
Go to the top of the page
+Quote Post
Start new topic
post Feb 22 2016, 03:03 PM
Post #2

Its GNU/

Group: Support Specialist
Posts: 1,797
Joined: 23-January 03
Member No.: 360

bash can only handle integer math so you need to use bc. There are other utilities that can do math too.
The following is untested but I think you will get the idea on using bc. You can find many examples by searching the web.

shear_sum[i]=$( echo "${shear1[i]} + ${shear2[i]}" | bc )
Go to the top of the page
+Quote Post

Posts in this topic

Reply to this topicStart new topic
1 User(s) are reading this topic (1 Guests and 0 Anonymous Users)
0 Members:


RSS Lo-Fi Version Time is now: 21st October 2017 - 10:00 PM