How to print new line character with echo?
Solution 1
The new line character with the echo
command is "\n". Taking the following example:
echo -e "This is line 1\nThis is line 2"
Would result in the output
This is line 1
This is line 2
The "-e" parameter is important here.
Solution 2
POSIX 7 says you can't
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 use printf
instead:
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.
Solution 3
I finally properly format this string with printf "$string"
. Thank you all.
Related videos on Youtube
user3318603
Updated on September 18, 2022Comments
-
user3318603 over 1 year
I dump a string with
hexdump
like this2031 3334 2e30 0a32 2032 3331 302e 000a
. It is clear that0x0a
is new line character, however, when I try to echo this string out, I always got1 430.2 2 13.0
-- the new line is replaced with a space, even I use the-e
flag.What may be the problem? Does the tailing
\0
ruin the output? Is there any alternatives to print0x0a
a new line?Thanks and Best regards.
-
Admin almost 12 yearswhen I try to echo this string out How exactly do you do that? What is the exact command you use?
-
Admin almost 12 years@Dennis I mean
echo -e
. Thanks, I find a solution. -
Admin about 9 yearsthe preferred solution is just to use
printf "...\n"
instead ofecho
. -
Admin over 8 years
-
-
michael about 9 yearsbtw, this
"echo -e ..."
relies on bash's echo to work correctly (e.g.,dash
will just print the "-e"); but '/bin/echo' may (or may not) also work. Unfortunately (perhaps appropriately), there are a lot of echo's around, and you don't really want to care about which one you're going to get. Using'printf "....\n"
is a more portable option across env's and shells. -
Izzy about 9 years@michael_n which is what the OP finally reverted too, in fact. But the question was explicitely stating "with echo" – hence my answer this way. Anyhow, it was not "with Bash" – so thanks for your pointing out those differences!
-
Peter Mortensen about 5 yearsWhat is this
$string
that you speak of? How is this connected to the question? What is does it not involve\n
as in the other two answers?