32

I have just stumbled upon the bash syntax:

foo=42
bar=$[foo+1] # evaluates an arithmetic expression

When I Googled for this, I found http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_03_04.html#sect_03_04_05:

3.4.6. Arithmetic expansion

Arithmetic expansion allows the evaluation of an arithmetic expression and the substitution of the result. The format for arithmetic expansion is:

$(( EXPRESSION )) 

...

Wherever possible, Bash users should try to use the syntax with square brackets:

$[ EXPRESSION ] 

However, this will only calculate the result of EXPRESSION, and do no tests...

In my bash man page I can only find the $(( EXPRESSION )) form such as:

foo=42
bar=$((foo+1)) # evaluates an arithmetic expression

So what tests are not performed with $[...] that do with $((...)), or is the $[...] just a legacy version of $((...))?

Community
  • 1
  • 1
Chen Levy
  • 15,438
  • 17
  • 74
  • 92

2 Answers2

40

The manpage for bash v3.2.48 says:

[...] The format for arithmetic expansion is:

     $((expression))

The old format $[expression] is deprecated and will be removed in upcoming versions of bash.

So $[...] is old syntax that should not be used anymore.

sth
  • 222,467
  • 53
  • 283
  • 367
  • 7
    Note that exact text is not in [*the* bash man page](http://tiswww.case.edu/php/chet/bash/bash.html), it's in *some* bash man pages (e.g. [Debian patch this](http://patch-tracker.debian.org/patch/series/view/bash/4.1-3/man-arithmetic.dpatch)). The feature has been deprecated since bash-2.0, but persists today (bash-4.2). – mr.spuratic Apr 17 '14 at 11:49
13

@sth is entirely correct. And in case you are curious about why a more verbose syntax is now in favor, check out this old email from the mailing list.

http://lists.gnu.org/archive/html/bug-bash/2012-04/msg00033.html

In early proposals, a form $[expression] was used. It was functionally equivalent to the "$(())" of the current text, but objections were lodged that the 1988 KornShell had already implemented "$(())" and there was no compelling reason to invent yet another syntax. Furthermore, the "$[]" syntax had a minor incompatibility involving the patterns in case statements.

I am not sure that I like the rationale “but someone has already done this more verbosely,” but there you have it—maybe the case-statement problem was more compelling than I am imagining from this obscure mention?

Brandon Rhodes
  • 83,755
  • 16
  • 106
  • 147