Home > front end >  Why assignment inside loop not influence the global value?
Why assignment inside loop not influence the global value?

Time:05-14

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?

CodePudding user response:

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"
  •  Tags:  
  • bash
  • Related