Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 997
Quentin Avatar asked Nov 18 '15 16:11

Quentin


2 Answers

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.

like image 194
Etan Reisner Avatar answered Nov 07 '22 23:11

Etan Reisner


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.

like image 22
cuonglm Avatar answered Nov 08 '22 00:11

cuonglm