Bash 与使用命令 `echo -ne "hello\n"` 的 Dash 行为对比

Bash vs. Dash behavior with the command `echo -ne "hello\n"`

我使用相同的命令 echo -ne "hello\n" 和 bash 以及破折号得到了不同的行为。见下文:

$ bash -c 'echo -ne "hello\n"'
hello
$ dash -c 'echo -ne "hello\n"'
-ne hello

这是为什么?完全不懂…

我的系统:

$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 12.04.5 LTS
Release:    12.04
Codename:   precise

echo 的 POSIX 规范不支持任何参数。看到了here.

虽然规范中提到了 -n,但这样做是说它 不是 一个选项,它要么是一个实现定义的案例,要么被视为一个字符串.

所以 dash 正是这样做的。

另一方面,

bash 在很多方面都有不合规的行为。

这就是为什么通常不鼓励使用 echo 以支持使用 printf 的原因,后者具有更好的规范和更好的可移植性。

虽然 bash 中的 echo 实现不是 POSIX 并且默认符合 Unix,但您可以在 运行 时间或编译时间更改其行为。

在 运行 时间,在 xpg_echo 和 POSIX 模式下,bash echo 变得一致:

$ env BASHOPTS=xpg_echo SHELLOPTS=posix bash -c 'echo -ne "hello\n"'
-ne hello

或:

$ env BASHOPTS=xpg_echo POSIXLY_CORRECT= bash -c 'echo -ne "hello\n"'
-ne hello

在编译时,您可以将 --enable-xpg-echo-default--enable-strict-posix-default 选项传递给 configure 脚本。