why echo `echo -e "abc\nabc"` gives me "abc abc"?

Jiapei Zhang :

A question about linux-shell.

When I type

echo `echo -e "abc\nabc"`,

I got abc abc not abc\nabc

Benjamin W. :

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 (and printf) behaves in different shells
  • The POSIX spec for echo with the recommendation to rather use printf instead

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=174268&siteId=1