[clue] arithmetic in bash

Aaron D. Johnson adj at fnord.greeley.co.us
Thu Apr 12 11:14:55 MDT 2012


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


More information about the clue mailing list