bash: $[<算术表达式>] vs. $((<算术表达式>)) [英] bash: $[<arithmetic-expression>] vs. $((<arithmetic-expression>))
问题描述
我刚刚偶然发现了 bash 语法:
I have just stumbled upon the bash syntax:
foo=42
bar=$[foo+1] # evaluates an arithmetic expression
当我为此在 Google 上搜索时,我发现了 http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_03_04.html#sect_03_04_05:
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 allows the evaluation of an arithmetic expression and the substitution of the result. The format for arithmetic expansion is:
$(( EXPRESSION ))
...
在可能的情况下,Bash 用户应该尝试使用带方括号的语法:
Wherever possible, Bash users should try to use the syntax with square brackets:
$[ EXPRESSION ]
不过,这只会计算EXPRESSION的结果,不做测试...
However, this will only calculate the result of EXPRESSION, and do no tests...
在我的 bash 手册页中,我只能找到 $(( EXPRESSION ))
形式,例如:
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 $((...))
?
推荐答案
bash v3.2.48 的联机帮助页说:
The manpage for bash v3.2.48 says:
[...] 算术展开的格式为:
[...] The format for arithmetic expansion is:
$((expression))
旧格式 $[expression] 已弃用,并将在即将推出的版本中删除bash.
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.
这篇关于bash: $[<算术表达式>] vs. $((<算术表达式>))的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!