[buug] loops and pipe sinks are subshells, aaaargh
Ian Zimmerman
itz at buug.org
Thu Aug 4 15:21:04 PDT 2011
Sigh. When I wrote my post I assumed the problem I described would be
instantly recognized by any Unix veteran who (I kept assuming) had run
into it themselves many times before, and who would be able to suggest a
neat way around it. I was wrong.
So let's start again. Here's a hypothetical but reasonably practical
example, unlike the schematic examples I posted before.
You have a program output_foo that spews lines line these:
foo 1
bar 23
baz 4
foo 53
foobar 6
...
Note there are repetitions. Now let's say you want a script that sums
up all of "foo" lines, and for some reason you want to use sh (and not
perl or python etc.) How would you do it? Well, the obvious way:
total=0
output_foo |
while read item count ; do
if [ $item = foo ] ; then
total=`expr $total+ $count`
fi
done
echo $total
won't work, for precisely the reasons my schematic scripts before
failed. (It will echo 0).
Your turn.
--
Ian Zimmerman
gpg public key: 1024D/C6FF61AD
fingerprint: 66DC D68F 5C1B 4D71 2EE5 BD03 8A00 786C C6FF 61AD
Rule 420: All persons more than eight miles high to leave the court.
More information about the buug
mailing list