\n doesn't work on terminal
By default, the standard GNU version of echo
delivered with Ubuntu, doesn't recognize escape sequences. Use the -e
flag to enable that.
Compare the outputs:
serg@ubuntu(bash):[/home/xieerqi]$ echo "new\nline"
new\nline
serg@ubuntu(bash):[/home/xieerqi]$ echo -e "new\nline"
new
line
In general echo
in scripts isn't recommended. For instance, mksh
version of echo
does allow interpreting the escapes.
For portability of scripts, use the printf
function.
serg@ubuntu(bash):[/home/xieerqi]$ printf "new\nline\n"
new
line
The answer by Serg solves only the problem with printing newline (echo
, printf
). If you need to use newline in general in shell scripts here are some suggestions which demostrate use of a newline by storing it to a variable $NL
. When the code works correctly echo "a${NL}b"
then prints:
a
b
POSIX compliant sh
You can use a literal newline:
NL="
"
You can generate the newline using printf
and command substitution:
NLx="$(printf \\nx)" ; NL="${NLx%x}"
The appending of x
and the following removal of it is necessary because the command substitution removes all newlines at the end of the resulting string.
Bash
In Bash you can use escape sequences to represent control characters in a string between $'
and '
:
NL=$'\n'
This is very convenient but unfortunately not portable.