Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

echo -e backslash escapes not being respected in sh

I have a shell script that I wish to run on different Linux servers. When I run the echo command with the -e option and escape characters in the string it doesn't execute as expected on the sh shell on Ubuntu 12.04 or Ubuntu 11.04. The two servers we have in use that I would like the script to work on are running CentOS 5.3 and Ubuntu 12.04. When I run the following command in bash on the two servers the expected output is produced:

$ echo -e "line1\nline2"
line1
line2

When I run the same command in sh on the CentOS machine the correct output is also produced. But when I run the command in sh on Ubuntu 12.04 or 11.04 the following output is produced:

$ echo -e "line1\nline2"
-e line1
line2

Interesting if I run the below in sh on Ubuntu it automatically interprets the escape characters.

$ echo "line1\nline2"
line1
line2

The script needs to run in the sh shell and should be portable across different machines. Any solutions. I'd also much appreciate a link to some docs explaining why or how this stuff happens.

like image 630
Marwan Alsabbagh Avatar asked Oct 22 '12 05:10

Marwan Alsabbagh


1 Answers

The sh shell in Ubuntu is dash. Its built-in echo doesn't have an -e option (and consequently it simply echoes it, as you saw), or, rather, it doesn't have a way of turning the escape behaviour off.

Use /bin/echo instead.

To check what shell you're using try echo $SHELL

$ echo $SHELL
/bin/bash
like image 146
rici Avatar answered Sep 21 '22 06:09

rici