echo outputs -e parameter in bash scripts. How can I prevent this?

Sam Svenbjorgchristiensensen picture Sam Svenbjorgchristiensensen · Dec 14, 2010 · Viewed 22.4k times · Source

I've read the man pages on echo, and it tells me that the -e parameter will allow an escaped character, such as an escaped n for newline, to have its special meaning. When I type the command

$ echo -e 'foo\nbar'

into an interactive bash shell, I get the expected output:

foo
bar

But when I use this same command (i've tried this command character for character as a test case) I get the following output:

-e foo
 bar

It's as if echo is interpretting the -e as a parameter (because the newline still shows up) yet also it interprets the -e as a string to echo. What's going on here? How can I prevent the -e showing up?

Answer

Dennis Williamson picture Dennis Williamson · Dec 14, 2010

You need to use #!/bin/bash as the first line in your script. If you don't, or if you use #!/bin/sh, the script will be run by the Bourne shell and its echo doesn't recognize the -e option. In general, it is recommended that all new scripts use printf instead of echo if portability is important.

In Ubuntu, sh is provided by a symlink to /bin/dash.