[ale] simple math in bash
Geoffrey Myers
geof at abraxis.com
Mon Nov 17 23:50:08 EST 1997
Chris Hamilton wrote:
> > > I can't remember how to do simple math in bash. I used to know but I cant find
> >
> > Don't know whether there is an easier way, but, I have always
> > used "dc" to do math in shell scripts. Ex, adding 1 + 1 would be:
> >
> > echo "1 1 + p q" | dc
>
> I either use bc (interactively) or expr.
>
> E.g. $ expr 1 + 1
expr is a hog, using the foo=$((1 + 1)) is much faster. A little benchmarking, first
ksh:
i=0;
time while [ $i -le 1000 ]; do
i=`expr $i + 1`
done;print $i
1001
32.47s real 0.89s user 2.29s system
i=0;
time while [ $i -le 1000 ]; do
((i=i + 1))
done;print $i
1001
0.45s real 0.42s user 0.00s system
Some real major diffences. This is ksh, but the tests under bash ( using the i=$((i
+ 1)) ) although not as impressive as ksh, they are substantial. Same while loop:
i=`expr $i + 1`
14.36user 13.50system 0:35.38elapsed 78%CPU (0avgtext+0avgdata 0maxresident)k
i=$((i + 1))
8.65user 0.01system 0:09.28elapsed 93%CPU (0avgtext+0avgdata 0maxresident)k
So, if you're going to do math, better use ksh. :)
>
>
> Spang!
>
> ---
> Christopher Hamilton Internal System Administrator
> chrish at ifsintl.com IFS International, Inc.
--
Until later: Geoffrey geof at abraxis.com
More information about the Ale
mailing list