Benoît P
Benoît P

Reputation: 3265

Why does "\\\\" equals "\\" in zsh?

So to write a backslash to stdout you do

zsh$ echo \\
\

You would think that to output 2 backslashes, you need to run this:

zsh$ echo \\\\
\

Wrong, You need 6 or 8:

zsh$ echo \\\\\\
\\
zsh$ echo \\\\\\\\
\\

Why on earth would I need 8 backslashes ?

Behaviors in different shells :

ksh$ echo \\\\
\\
zsh$ echo \\\\
\
bash$ echo \\\\
\\
sh$ echo \\\\
\
csh$ echo \\\\
\\

Backslashes

Upvotes: 2

Views: 198

Answers (2)

Vengleab SO
Vengleab SO

Reputation: 814

Not only zsh, it's default behavior in terminal, backslash (\) is a special character used to tell bash script that you want to other params/texts in newline, so to avoid newline,u need add another backslash to escape special character, since backslash also used for escape special character

Upvotes: 0

chepner
chepner

Reputation: 531758

You are probably used to bash's built-in echo, which does not perform expansion of escape sequences. POSIX echo, however, does. zsh follows the POSIX specification, so when you write echo \\\\\\, here's what happens.

  1. Quote removal reduces \\\\\\ to \\\; each escaped \ becomes a literal \.
  2. echo takes the three \ it receives, and replaces the first \\ with \. The remaining \ doesn't precede anything, so it is treated literally.
  3. The final result is an output of two \.

With echo \\\\\\\\, here's what happens.

  1. As before, \\\\\\\\ becomes \\\\, because each pair of backslashes becomes a single \ after quote removal.
  2. echo takes the 4 backslashes, and replaces the first \\ with \ and the second \\ with \ as well, since this time it received two matched pairs.
  3. The final result is again two \.

bash probably inherited its non-POSIX comformance from ksh, sh is by definition a POSIX-comformant shell, and it's best not to think about what csh is doing.

Upvotes: 4

Related Questions