6

\n is not recognized as "change line". It just prints \n.

My terminal is gnome terminal 3.6.2.

First I noticed it with echo commands,and then with shell scripts.

Any suggestions as to why it doesn't work?

muru
  • 207,228
PaschalisAv
  • 143
  • 1
  • 1
  • 6

2 Answers2

10

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
Fabby
  • 35,017
2

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.