'Why assignment inside loop not influence the global value?

I have next data source and code:

data:

1
2
3

test.sh:

s=0
cat data | while read oneline
do
    v=$(($oneline))
    s=$(($s+$v))
    echo $s
done
echo "Final: $s"

Execution:

$ ./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?



Solution 1:[1]

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"

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Orion