The purpose of my script is to count how many lines there are in a
file. I know I could use
wc for example but the purpose of this exercise is to understand processes and pipelines in Linux.
The script executed on my terminal:
C=0; cat file | while read line ; do C=$[ $C + 1 ] ; done ; echo $C
I always get
0 or whatever number I inizialize
In my textbook they explain this behavior saying that for every pipeline a new child process is created, it inherits all father variables but when the child dies the father still "see" his old values. And I'm ok with that.
What I don't understand is that I only see one pipeline, between
C=0; cat file and
while read line ; do C=$[ $C + 1 ] ; done ; echo $C. So I'm guessing that the second part is executed by the child (
echo too) so why it prints the wrong value? Shouldn't the child increase
C variable AND print the correct value as it belongs to the same pipe?