[clue] arithmetic in bash
David L. Willson
DLWillson at TheGeek.NU
Thu Apr 12 12:11:35 MDT 2012
Aaron,
Thanks for the well-thought-out answer. I'll return to using '$(( EXPRESSION ))', even though I can depend on bash for all my work.
I guess that '$[ EXPRESSION ]' has some capabilities over the old style, but I never do anything terribly complex.
In my specific application, getting some random numbers, '$(( EXPRESSION ))' is working perfectly.
Case in point:
# Generate a bunch of random looking numbers, in the range 1 to 10, inclusive.
while true ; do echo -n "$(( RANDOM % 10 + 1 )) " ; done
--
David L. Willson
Trainer, Engineer, Enthusiast
RHCE Network+ A+ Linux+ LPIC-1 Ubuntu
Mobile 720-333-LANS(5267)
This is a good time for a r3volution.
----- Original Message -----
> David L. Willson writes:
> > Why are the square brackets preferred (see below)? Why are there
> > two
> > forms?
>
> I probably don't have this completely correct, but... I'd say the
> recommendation is incorrect.
>
> It is my understanding that the $(( ... )) syntax is a POSIX shell
> feature, while the $[ ... ] is something that bash added in the
> early-mid 1990s. Given that, I try to use the $(( ... )) syntax
> exclusively. The $[ .. ] syntax generally doesn't work on non-bash
> Bourne shells. This may or may not be a concern for you.
>
> Please stand by while I fire up the HP-UX box...
>
> Here's what happens with $[ .. ] on a non-bash Bourne style shell:
>
> $ SHELL=/usr/bin/sh; exec $SHELL -o vi
> $ uname -a
> HP-UX billandd B.11.23 U 9000/800 1822910606 unlimited-user
> license
> $ echo $((2 * 5))
> 10
> $ echo $[2 * 5]
> $[2 fileset-cleanup 5]
> $ exit
>
> Compare with the results on a machine using bash:
>
> adj at sacredchao:~$ echo $SHELL
> /bin/bash
> adj at sacredchao:~$ uname -a
> Linux sacredchao 3.2.0-0.bpo.1-amd64 #1 SMP Sat Feb 11 08:41:32
> UTC 2012 x86_64 GNU/Linux
> adj at sacredchao:~$ echo $((2 * 5))
> 10
> adj at sacredchao:~$ echo $[2 * 5]
> 10
> adj at sacredchao:~$
>
> Googling for "bashism" will turn up many similar instances where Chet
> and crew added non-standard stuff to bash, and the efforts needed to
> weed them out when they're used in non-bash environments.
>
> To sum up: I disagree with the recommendation in the Bash Guide for
> Beginners. Use the POSIX syntax for arithmetic. But if you can
> guarantee your scripts will run on nothing but bash, do whatever
> tickles your fancy.
>
> - Aaron
> _______________________________________________
> clue mailing list: clue at cluedenver.org
> For information, account preferences, or to unsubscribe see:
> http://cluedenver.org/mailman/listinfo/clue
>
More information about the clue
mailing list