Path: utzoo!utgpu!news-server.csri.toronto.edu!clyde.concordia.ca!uunet!auspex!guy From: guy@auspex.auspex.com (Guy Harris) Newsgroups: comp.unix.questions Subject: Re: What's wrong with this Bourne shell script? Message-ID: <3821@auspex.auspex.com> Date: 5 Aug 90 00:41:06 GMT References: <1990Aug3.193231.3166@silma.com> Organization: Auspex Systems, Santa Clara Lines: 27 >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.)