我在bash和dash中运行程序时得到了不同的输出结果。
#!/bin/sh
echo $SHELL
n=1
a=$((++n))
echo $n
Bash:
$ bash shell_test.sh
2
仪表板:
$ dash shell_test.sh
1
我在bash和dash中运行程序时得到了不同的输出结果。
#!/bin/sh
echo $SHELL
n=1
a=$((++n))
echo $n
Bash:
$ bash shell_test.sh
2
仪表板:
$ dash shell_test.sh
1
dash
是Debian Almquist shell,它是一个极端轻量级的完整POSIX-compliant的/bin/sh
实现版本,旨在尽可能小以创建更快的启动时间。
像$((n++))
,$((--n))
等运算符是不需要POSIX要求的功能,因此没有实现。
了解dash如何解释这些语句,请参见Chepner的答案
一篇很好的页面,介绍如何使脚本符合POSIX标准,可以在这里找到。
2.6.4 Arithmetic Expansion: Arithmetic expansion provides a mechanism for evaluating an arithmetic expression and substituting its value. The format for arithmetic expansion shall be as follows:
$((expression))
The expression shall be treated as if it were in double-quotes, except that a double-quote inside the expression is not treated specially. The shell shall expand all tokens in the expression for parameter expansion, command substitution, and quote removal.
Next, the shell shall treat this as an arithmetic expression and substitute the value of the expression. The arithmetic expression shall be processed according to the rules given in Arithmetic Precision and Operations, with the following exceptions:
- Only signed long integer arithmetic is required.
- Only the decimal-constant, octal-constant, and hexadecimal-constant constants specified in the ISO C standard, Section 6.4.4.1 are required to be recognized as constants.
- The
sizeof()
operator and the prefix and postfix++
and--
operators are not required.- Selection, iteration, and jump statements are not supported.
source: POSIX IEEE Std 1003.1-2017
POSIX并不要求使用前缀++
,而dash
也不支持它。相反,它会被解析为两个一元的+
操作符:
$ n=1
$ echo $((+(+n)))
1
$ echo $((++n))
1
$ echo $n
1