September 2018
Beginner
186 pages
4h 30m
English
When passing program output into a compound command with a pipe, there's a subtle pattern of problems, which can be very hard to figure out, to do with subshells.
Consider this simple loop, which is intended to count the lines of output from a call to who, and then print it:
((count = 0))
who | while read -r ; do
((count++))
done
printf '%u\n' "$count"
When run, however, this program always prints zero for the count! Most new shell programmers eventually run into this sort of particularly baffling problem.
Because each command after the first command in a pipeline runs in its own subshell environment—its own forked process—changes to variables do not persist after the pipeline is completed. This means that the ...
Read now
Unlock full access