Echo newline in Bash prints literal \n
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.
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.
Popular Answer
Are you sure you are in bash? Works for me, all four ways:
echo -e "Hello\nworld"
echo -e 'Hello\nworld'
echo Hello$'\n'world
echo Hello ; echo world
Read more... Read less...
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.
Try
echo -e "hello\nworld"
hello
world
worked for me in nano
editor.
From the man page:
-e
enable interpretation of backslash escapes
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;
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.