Why does the following command not insert new lines in the generated file and what's the solution?
$ echo "Line 1\r\nLine2" >> readme.txt
$ cat readme.txt
Line 1\r\nLine2
echostdout
Why does the following command not insert new lines in the generated file and what's the solution?
$ echo "Line 1\r\nLine2" >> readme.txt
$ cat readme.txt
Line 1\r\nLine2
Best Answer
echo
An
echo
implementation which strictly conforms to the Single Unix Specification will add newlines if you do:But that is not a reliable behavior. In fact, there really isn't any standard behavior which you can expect of
echo
.And so there really isn't any general way to know how to write a newline with
echo
, except that you can generally rely on just doingecho
to do so.A
bash
shell typically does not conform to the specification, and handles the-n
and other options, but even that is uncertain. You can do:And not even that is necessary if
bash
has been built with the build-time option...printf
On the other hand,
printf
's behavior is pretty tame in comparison.It handles format strings which describe its arguments - which can be any number of things, but for strings are pretty much either
%b
yte strings or literal%s
trings. Other than the%f
ormats in the first argument, it behaves most like a%b
yte string argument, except that it doesn't handle the\c
escape.See Why is
printf
better thanecho
? for more.echo() printf
You might write your own standards conformant
echo
like......which should pretty much always do the right thing automatically.
Actually, no... That prints a literal
\n
at the tail of the arguments if the last argument ends in an odd number of <backslashes>.But this doesn't: