Reputation: 41
In bash, anything between single quotes will remain its literal meaning, but when I type "echo '\n'" in my terminal. The output I get is a newline instead of the expected '\n' character.
Upvotes: 1
Views: 531
Reputation: 1163
Checked this using bash and zsh under macos Catalina.
Upvotes: 0
Reputation: 52344
According to the POSIX spec for echo
:
If the first operand is -n, or if any of the operands contain a
<backslash>
character, the results are implementation-defined.
echo
is normally a shell builtin, and zsh
's will interpret backlash escapes by default. You can use echo -E
, which tells both the zsh
and bash
versions of echo
to disable treating them specially. zsh
also uses the BSD_ECHO
shell option to control this behavior:
$ echo "\n"
$ echo -E "\n"
\n
$ setopt BSD_ECHO
$ echo "\n"
\n
The most portable alternative, though, is using printf
instead of echo
, as it doesn't rely on any shell-specific behaviors:
$ printf '\\n\n'
\n
Upvotes: 4