Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why assignment inside loop not influence the global value?

I have next data source and code:

data:

1
2
3

test.sh:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 :

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"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading