I encountered a behaviour that I don't understand while testing a script that sums the outputs from repeated executions of a program. To reproduce it create the text files out, which represents the output of my program, and sum, the file that holds the sum of the values returned on previous executions and which starts out as a copy of out,
cat > out << EOF
2 20
5 50
EOF
cp out sum
The strange thing happens on running
paste out sum | awk '{$1 += $3; $2 += $4; NF = 2; print}' | tee sum
several times (15-20 times might be needed). Each time it runs, this command should add to the values in sum the corresponding values in out and write the results back to sum. What I get is that it works an unpredictable number of times, then sum reverts back to
2 20
5 50
I have later learned that I cannot redirect or tee output to the same file I'm working on and solved the issue using a temporary file, still, this behaviour baffles me:
- why does - … | tee sumwork at all (even if only for a limited number of iterations), while- … > sumnever overwrites- sum?
- why doesn't it work a predictable number of times? 



sum?paste out sum | awk '{$1 += $3; $2 += $4; NF = 2; print}' > sum. If you try that and thencat sum, you should see thatsumhas not changed.