Nin
Nin

Reputation: 41

echo program prints newline instead of '\n'

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

Answers (2)

WolfiG
WolfiG

Reputation: 1163

Checked this using bash and zsh under macos Catalina.

  • bash: $echo '\n’ produced "\n"
  • zsh: %echo '\n' produced newline
  • zsh: %echo '\n' produces "\n"

Upvotes: 0

Shawn
Shawn

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

Related Questions