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

Re: Recomended tutoial(s) on doing arithmetic in Bash scripts



-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

On Mon, Mar 06, 2017 at 08:38:05AM -0500, Greg Wooledge wrote:
> On Sun, Mar 05, 2017 at 05:25:49PM +0100, tomas@tuxteam.de wrote:
> > If you need floating point numbers, bc (or dc) are your next stops.
> 
> Or awk.  For some problems, awk is fantastic.
> 
> 
> On Sun, Mar 05, 2017 at 06:14:00PM +0000, GiaThnYgeia wrote:
> > I see your 2 and raise you
> > nosuchagency@bottomofthesea:~$ echo $(((3000000000+4000000000)/3))
> > 2333333333
> > 
> > Infinitely inaccurate digital systems
> 
> Bash uses 64-bit integers, since version 2.05b.  If you want arbitrary
> precision, use bc (or a programming language with an arbitrary precision
> math library).

As I found out, dc also supports arbitrary precision. Had I read the
man page's "NAME" entry

  NAME
       dc - an arbitrary precision calculator

with some more care, oh, well.

> POSIX shells in general may use smaller integers than that.  I wouldn't
> expect anything outside the range (-2^31 .. +2^31) to be portable.

Yes. Proceed with care.

> expr(1) is legacy rubbish and should never be used in new scripts.

It's from the times shells hadn't built-in arithmetic. If you are stuck
with, e.g. an old c shell (some over-expensive commercial application
at $COMPANY is), you might find calls to it deeply buried in shell
primordial soup. So it makes sense to keep it around. But yes, what
expr can do can/should be done (better) by $((...))

regards
- -- t
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.12 (GNU/Linux)

iEYEARECAAYFAli9aX8ACgkQBcgs9XrR2kZ0kwCfRml26cNAb7uvl31UkB/gz+Ch
MMIAnjdfsjuUgpQ/JoP3Slha3I/OsQXQ
=czPp
-----END PGP SIGNATURE-----


Reply to: