Advertisement
Advertisement


Echo newline in Bash prints literal \n


Question

In Bash, tried this:

echo -e "hello\nworld"

But it doesn't print a newline, only \n. How can I make it print the newline?

I'm using Ubuntu 11.04.

2016/03/27
1
2481
3/27/2016 9:46:03 AM

Accepted Answer

You could use printf instead:

printf "hello\nworld\n"

printf has more consistent behavior than echo. The behavior of echo varies greatly between different versions.

2015/05/20
3012
5/20/2015 2:46:18 PM


echo $'hello\nworld'

prints

hello
world

$'' strings use ANSI C Quoting:

Words of the form $'string' are treated specially. The word expands to string, with backslash-escaped characters replaced as specified by the ANSI C standard.

2015/03/12

You could always do echo "".

e.g.

echo "Hello"
echo ""
echo "World"
2016/06/07

Try

echo -e "hello\nworld"
hello
world

worked for me in nano editor.

From the man page:

-e enable interpretation of backslash escapes

2019/12/04

In the off chance that someone finds themselves beating their head against the wall trying to figure out why a coworker's script won't print newlines, look out for this ->

#!/bin/bash
function GET_RECORDS()
{
   echo -e "starting\n the process";
}

echo $(GET_RECORDS);

As in the above, the actual running of the method may itself be wrapped in an echo which supersedes any echos that may be in the method itself. Obviously I watered this down for brevity, it was not so easy to spot!

You can then inform your comrades that a better way to execute functions would be like so:

#!/bin/bash
function GET_RECORDS()
{
   echo -e "starting\n the process";
}

GET_RECORDS;
2013/08/08

POSIX 7 on echo

http://pubs.opengroup.org/onlinepubs/9699919799/utilities/echo.html

-e is not defined and backslashes are implementation defined:

If the first operand is -n, or if any of the operands contain a <backslash> character, the results are implementation-defined.

unless you have an optional XSI extension.

So I recommend that you should use printf instead, which is well specified:

format operand shall be used as the format string described in XBD File Format Notation [...]

the File Format Notation:

\n <newline> Move the printing position to the start of the next line.

Also keep in mind that Ubuntu 15.10 and most distros implement echo both as:

  • a Bash built-in: help echo
  • a standalone executable: which echo

which can lead to some confusion.


Source: https://stackoverflow.com/questions/8467424
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]