[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [MiNT] counting up in bash



Hi!

On Mon, Dec 09, 2002 at 03:05:28PM +0100, Thomas Binder wrote:
> If you really don't care whether it's bash-only, I'd suggest the
> following
> 
> sum=0
> while read -r number
> do
> 	sum=$(($sum + $number))
> done < file-with-numbers
> echo "Sum is: $sum"

Just in case anyone wants to now how to do it in plain sh:

-- snip --
#
# Make file descriptor 3 a duplicate of stdin and redirect stdin
# to the file containing the numbers
#
exec 3<&0 < file-with-numbers

sum=0
while read number
do
        sum=`expr $sum + $number`
done
echo "Sum is: $sum"

#
# Make stdin a duplicate of file descriptor 3 (i.e. restore the
# original stdin) and close file descriptor 3
#
exec <&3 3<&-
-- snap --

Those strange input redirections are necessary because a while
loop with redirections may run in a subshell. Also beware that
this version runs A LOT longer (especially on larger input files)
due to the (necessary) use of backtick commands.

Note: A fully POSIX compliant sh should support $((...)) for
arithmetic expansion, but unfortunately, on most systems (e.g.
Solaris, IRIX), /bin/sh is not.


Ciao

Thomas


-- 
Thomas Binder (Gryf @ IRCNet)
gryf@hrzpub.tu-darmstadt.de
PGP-key available on request!