Backslash Escape Character in command echo

55 Views Asked by At

Can anyone explain why \n is not working as line break?

[user1@localhost ~]$ echo -e a\nb\nc
anbnc
2

There are 2 best solutions below

0
Gilles Quénot On

Use more quotes!

$ echo -e 'a\nb\nc'
a
b
c

or even better:

$ printf 'a\nb\nc'

Learn how to quote properly in shell, it's very important:

"Double quote" every literal that contains spaces/metacharacters and every expansion: "$var", "$(command "$var")", "${array[@]}", "a & b". Use 'single quotes' for code or literal $'s: 'Costs $5 US', ssh host 'echo "$HOSTNAME"'. See
http://mywiki.wooledge.org/Quotes
http://mywiki.wooledge.org/Arguments
https://web.archive.org/web/20230224010517/https://wiki.bash-hackers.org/syntax/words
when-is-double-quoting-necessary

0
user1934428 On

A backslash is interpreted by bash to escape the subsequent character. For instance, foo \* passes an asterisk to foo instead of doing globbing. Similarily, foo \x passes a literal x to foo; escaping is unnecessary, but not forbidden. In your case, the shell turns a\nb\nc into anbnc.

If you want to pass a literal backslash, you have to use \\ , for instance

echo -e a\\nb\\nc

Or you use use single quotes, which escape the whole content in one go:

echo -e 'a\nb\nc'

Or you don't rely on echo doing the newlines, but insert them explicitly:

echo  $'a\nb\nc'

Or with a HERE document, in which case you have to use cat instead of echo:

cat <<EE
a
b
c
EE