Echo -e backslash not respected in sh

I have a shell script that I want to run on different Linux servers. When I run the echo command with the -e option and escape characters in a string, it does not execute as expected on the sh shell on Ubuntu 12.04 or Ubuntu 11.04. The two servers that we use for which I would like to run the script are working with CentOS 5.3 and Ubuntu 12.04. When I run the following command in bash on two servers, the expected result is returned:

$ echo -e "line1\nline2" line1 line2 

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

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

Interestingly, if I ran below in sh on Ubuntu, it will automatically interpret the escape characters.

 $ echo "line1\nline2" line1 line2 

The script must run in the sh shell and must be portable on different machines. Any decisions. I also really appreciate the link to some documents explaining why and how this happens.

+4
source share
2 answers

The sh shell in Ubuntu dash . Its built-in echo does not have the -e option (and therefore, it just drives it away, as you saw), or rather, it has no way to disable the escape code behavior.

Use /bin/echo instead.

To check which shell you use try echo $SHELL

 $ echo $SHELL /bin/bash 
+5
source

echo hopelessly incompatible between implementations; if you require consistent behavior for non-trivial applications (e.g. escape sequences), use printf instead (and don't forget to add the final \ n explicitly):

 $ printf "line1\nline2\n" line1 line2 
0
source

Source: https://habr.com/ru/post/1441196/


All Articles