I have next
data source and
1 2 3
s=0 cat data | while read oneline do v=$(($oneline)) s=$(($s+$v)) echo $s done echo "Final: $s"
$ ./test.sh 1 3 6 Final: 0
What I want to do is sum all values in the data file, you could see the
echo inside loop successfully print the sum step by step, but outside the loop, we got
Final: 0, it should be
Final: 6. What mistake did I make?
Pipes create subshells. The while read is running on a different shell than your script. The following will fix it
s=0 while read oneline do v=$(($oneline)) s=$(($s+$v)) echo $s done < data echo "Final: $s"