POSIX+XSI compliant echo
implementations output 2 newline characters when invoked with a \n
as argument as it requires it to expand \n
into a newline character. The echo
builtin of your sh
seems to be compliant in that regard.
Some other echo
implementations require a -e
option for that to happen even though POSIX requires echo -e
to output -e
. (that will change in future versions of the POSIX specification where the behaviour will be unspecified instead (except for those systems implementing the XSI option)).
For those reasons and more, it's better to avoid echo
and use printf
instead. See Why is printf better than echo? for details.
In any case, in all Bourne like shells, within double quotes, \
is only special when in front of the \
, $
, "
and `
characters (whose special meaning it removes) and newline (which causes it to be removed, \<NL>
is a line-continuation), not n
. So in:
echo '\n'
echo "\n"
echo \\n
echo $'\\n'
It's the string made of the two characters \
and n
that is passed to echo
(at least when that code is not within `...`
for the last 2).
For a string made of one newline character to be passed, you'd need:
echo $'\n'
That's ksh93 syntax now supported by many other Bourne-like shells. Portably (in Bourne-like shells):
echo '
'
echo "
"
Though you may want to make it:
# at the top of the script:
NL='
'
# or (with the Bourne shell, use `...` instead):
eval "$(printf 'NL="\n" CR="\r" TAB="\t"')"
# and then:
echo "$NL"
To improve legibility.
Note that the situation will be different in non-Bourne-like shells. See How to use a special character as a normal one? for details on that.
dash
prints two empty lines, it is POSIX compliant with respect toecho
, since the POSIX base +XSI extensions is required for a system that is permitted to use theUNIX
branding. – schily May 18 '20 at 06:46