I wrote below small script which will add up each row value from a file and print the total, but it is not.plz let me know what is wrong.script hangs and not displaying anything.
-----------------
while read line ; do
sum=0;
sum=$sum+$line;
done
echo $sum;
exit 0;
------------------
file has below rows:
37.17
65.53
106.14
45.12
The first thing I notice offhand is that you zero out the sum inside the while loop for every line.
But also, you don't display how you are getting the contents of the file to be read in the while loop. Can you show what you did there. If nothing, than that is the reason the script is "hanging". It's reading stdin which means it's awaiting your input.
Then there is the problem that you are working with floating point numbers. Does your shell handle that? Mine doesn't
You have solved a few problems. You've got the file contents going into the While loop so that's good, (I'm assuming the double $$ before FILE is just a typo, if not get rid of one '$' there).
You're not zeroing out the sum, IN the while loop. Also good.
But that leaves us with the fact that your still dealing with floating point numbers, not integers.
Do a 'man' on your shell and see if it supports 'typeset -E' or 'typeset -F'. If so, try using:
You will have to add it up manually to verify the correct answer, but if you're just using the numbers you gave us above as a test file, the answer would be 253.96.
If using typeset -F or typeset -E isn't working it's probably not supported.
vgresh99's response is perfect actually. You could wrap that up in a command substition to put the value into a variable for use elsewhere if needed.