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

你说的曾经没有我的故事 提交于 2019-12-10 14:23:55

问题


I got different behaviors with the same command echo -ne "hello\n" with bash and with dash. See below :

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

Why is that ? I don't understand at all…

My system :

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

回答1:


The POSIX specification for echo doesn't support any arguments. See it here.

And while the spec mentions -n it does so to say that it is not an option and is either an implementation defined case or to be treated as a string.

So dash is doing exactly that.

bash, on the other hand, has non-conforming behavior in a number of ways.

This is why the use of echo is generally discouraged in favor of the using printf which has a much better specification and much better portable behavior.




回答2:


While echo implementation in bash is not POSIX and Unix conformed by default, you can alter its behavior at run time or compile time.

At run time, with xpg_echo and in POSIX mode, bash echo became conformant:

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

or:

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

At compile time, you can pass --enable-xpg-echo-default and --enable-strict-posix-default options to configure script.



来源:https://stackoverflow.com/questions/33784892/bash-vs-dash-behavior-with-the-command-echo-ne-hello-n

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!