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?
Different implementations of
echo
behave in annoyingly different ways. Some don't take options (i.e. will simply echo-e
as you describe) and automatically interpret escape sequences in their parameters. Some take flags, and don't interpret escapes unless given the-e
flag. Some take flags, and interpret different escape sequences depending on whether the-e
flag was passed. Some will cause you to tear your hair out if you try to get them to behave in a predictable manner... oh, wait, that's all of them.What you're probably seeing here is a difference between the version of
echo
built intobash
vs/bin/echo
or maybe vs. some other shell's builtin. This bit me when Mac OS X v10.5 shipped with a bash builtinecho
that echoed flags, unlike what all my scripts expected...In any case, there's a solution: use
printf
instead. It always interprets escape sequences in its first argument (the format string). The problems are that it doesn't automatically add a newline (so you have to remember do that explicitly), and it also interprets%
sequences in its first argument (it is, after all, a format string). Generally, you want to put all the formatting stuff in the format string, then put variable strings in the rest of the arguments so you can control how they're interpreted by which%
format you use to interpolate them into the output. Some examples:Use
to force 'echo' invoking coreutils' echo which interpret '-e' parameter.
Try this:
Source: http://www.saltycrane.com/blog/2011/04/how-use-bash-shell-python-subprocess-instead-binsh/
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 itsecho
doesn't recognize the-e
option. In general, it is recommended that all new scripts useprintf
instead ofecho
if portability is important.In Ubuntu,
sh
is provided by a symlink to/bin/dash
.