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 into bash
vs /bin/echo
or maybe vs. some other shell's builtin. This bit me when Mac OS X v10.5 shipped with a bash builtin echo
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:
printf "foo\nbar\n" # this does what you're trying to do in the example
printf "%s\n" "$var" # behaves like 'echo "$var"', except escapes will never be interpreted
printf "%b\n" "$var" # behaves like 'echo "$var"', except escapes will always be interpreted
printf "%b\n" "foo\nbar" # also does your example