在脚本中,运算按照优先级顺序执行:优先级较高的运算先于优先级较低的运算执行。 [1]
表 8-1. 运算符优先级
| 运算符 | 含义 | 注释 | 
|---|---|---|
| 最高优先级 | ||
| var++ var-- | 后自增,后自减 | C 风格运算符 | 
| ++var --var | 前自增,前自减 | |
| ! ~ | 取反 | 逻辑 / 位运算,反转后续运算符的意义 | 
| ** | 求幂 | 算术运算 | 
| * / % | 乘法,除法,取模 | 算术运算 | 
| + - | 加法,减法 | 算术运算 | 
| << >> | 左移,右移 | 位运算 | 
| -z -n | 一元比较 | 字符串是/不是 空 | 
| -e -f -t -x, 等等 | 一元比较 | 文件测试 | 
| < -lt > -gt <= -le >= -ge | 复合比较 | 字符串和整数 | 
| -nt -ot -ef | 复合比较 | 文件测试 | 
| == -eq != -ne | 相等 / 不相等 | 测试运算符,字符串和整数 | 
| & | 与 | 位运算 | 
| ^ | 异或 | 异或,位运算 | 
| | | 或 | 位运算 | 
| && -a | 与 | 逻辑,复合比较 | 
| || -o | 或 | 逻辑,复合比较 | 
| ?: | 三元运算符 | C 风格 | 
| = | 赋值 | (不要与相等测试混淆) | 
| *= /= %= += -= <<= >>= &= | 组合赋值 | 乘等于,除等于,模等于,等等 | 
| , | 逗号 | 连接一系列运算 | 
| 最低优先级 | 
在实践中,你真正需要记住的是以下内容
用于熟悉的算术运算的 "My Dear Aunt Sally" 口诀(乘法,除法,加法,减法)。
复合逻辑运算符 &&、||、-a 和 -o 具有较低的优先级。
相同优先级的运算符的求值顺序通常是从左到右。
现在,让我们利用我们对运算符优先级的知识来分析几行来自/etc/init.d/functions 文件,正如在 Fedora Core Linux 发行版中发现的那样。
| while [ -n "$remaining" -a "$retry" -gt 0 ]; do
# This looks rather daunting at first glance.
# Separate the conditions:
while [ -n "$remaining" -a "$retry" -gt 0 ]; do
#       --condition 1-- ^^ --condition 2-
#  If variable "$remaining" is not zero length
#+      AND (-a)
#+ variable "$retry" is greater-than zero
#+ then
#+ the [ expresion-within-condition-brackets ] returns success (0)
#+ and the while-loop executes an iteration.
#  ==============================================================
#  Evaluate "condition 1" and "condition 2" ***before***
#+ ANDing them. Why? Because the AND (-a) has a lower precedence
#+ than the -n and -gt operators,
#+ and therefore gets evaluated *last*.
#################################################################
if [ -f /etc/sysconfig/i18n -a -z "${NOLOCALE:-}" ] ; then
# Again, separate the conditions:
if [ -f /etc/sysconfig/i18n -a -z "${NOLOCALE:-}" ] ; then
#    --condition 1--------- ^^ --condition 2-----
#  If file "/etc/sysconfig/i18n" exists
#+      AND (-a)
#+ variable $NOLOCALE is zero length
#+ then
#+ the [ test-expresion-within-condition-brackets ] returns success (0)
#+ and the commands following execute.
#
#  As before, the AND (-a) gets evaluated *last*
#+ because it has the lowest precedence of the operators within
#+ the test brackets.
#  ==============================================================
#  Note:
#  ${NOLOCALE:-} is a parameter expansion that seems redundant.
#  But, if $NOLOCALE has not been declared, it gets set to *null*,
#+ in effect declaring it.
#  This makes a difference in some contexts. | 
|  | 为了避免在复杂的测试运算符序列中出现混淆或错误,请将序列分解为带括号的部分。 
 | 
| [1] | 优先级,在这种上下文中,与 优先权 具有大致相同的含义 |