I have a very simple bash script to compute the sum of numbers appear at each line of a file (I know there are better ways for doing this but I actually need this sum as an auxiliary information and the script is supposed to something more later on). The script is as follows:
TOTAL=0;
cat $DATAFILE | while read LINE;
do
COUNT=`echo $LINE| awk '{print $2;}'`;
TOTAL=$((TOTAL+COUNT));
done
echo "Total = $TOTAL";
However, I always get the output "Total = 0". Surprisingly enough if I move the last line inside the while loop, I get the correct result. For example if the input file contains
A 5
B 3
C 6
I get the output
Total = 5
Total = 8
Total = 14
But the current version always outputs 0. It seems the value assigned to the variable TOTAL is somehow lost.
Can anyone help me out with the issue?
Thanks in advance