I use command | awk '{ print $1; }' | while read val ; do to loop through the command output. Recently I wanted to calculate the sum, and I discovered some strange behaviour in bash:
content of test.txt
100
200
300
content of test.sh
sum='0'
cat test.txt | awk '{ print $1; }' | while read val ; do
sum=`expr $sum + $val`
echo "sum is now: $sum"
done
echo "FINAL SUM: $sum"
output from executing test.sh
sum is now: 100
sum is now: 300
sum is now: 600
FINAL SUM: 0
the final sum should be 600. What can I do to fix this?