What's wrong with this Bourne shell script?
Guy Harris
guy at auspex.auspex.com
Sun Aug 5 10:41:06 AEST 1990
>The subtotal prints increasing numbers as you would expect.
>At the end total prints as 0!
>What gives?
You've been zapped by Mr. Subshell.
The Bourne shell runs some shell constructs in a sub-shell; apparently,
the construct you gave is one of them. This means that the "total=`expr
$total + $4` gets run in the same shell each time through the loop, so
the subtotal increases; however, that shell is a subshell of the one
that echoes "Total $total", and variable settings done inside subshells
do not affect the settings of variables in the parent shell. (To do so,
the subshell would have to inform the parent shell about them.)
This may change when shells become compliant with POSIX 1003.2, which
will presumably happen sometime after POSIX 1003.2 leaves the draft
stage and is approved; 1003.2 may put stricter controls on when a shell
may do something inside a subshell. I don't have recent drafts handy;
Maarten?
>While you're at it, is there a better way to get the total bytes
>of the files in a directory?
Will "du -s" do? It searches subdirectories of the given directory,
which your script doesn't; I suspect that's actually a bug in your
script, so "du -s" will do a better job. ("du -s" also tries to avoid
counting files with multiple hard links to them more than once.)
More information about the Comp.unix.questions
mailing list