A question about linux-shell.
When I type
echo `echo -e "abc\nabc"`
,
I got abc abc
not abc\nabc
Look at what the different layers do individually:
$ echo -e "abc\nabc"
abc
abc
because echo -e
expands backslash escapes such as \n
. (At least the one you used does; the behaviour is not consistent across shells.)
Then, you echo
that output, unquoted; this replaces any sequence of whitespace (including linebreaks) with a single blank character each ("word splitting").
$ str="abc
abc"
$ echo $str
abc abc
If you quote the string, whitespace is preserved (and shell special characters have no effect):
$ echo "$str"
abc
abc
You can achieve the same by quoting your command substitution:
$ echo "`echo -e \"abc\nabc\"`"
abc
abc
You have to escape the inner double quotes then, though. Which is one of the reasons why instead of backticks, these days it's recommended to use $(...)
for command substitution:
$ echo "$(echo -e "abc\nabc")"
abc
abc
And if this isn't just a learning example, be aware that echo "$(cmd)"
is usually an antipattern and should be replaced by just cmd
.
References
- This is a great overview of how
echo
(andprintf
) behaves in different shells - The POSIX spec for
echo
with the recommendation to rather useprintf
instead