bruce_ricard
bruce_ricard

Reputation: 771

Zsh escape backslash

I noticed a while ago already that in zsh, you can get a \ by typing \\ like in bash.

> echo \\
\

But, there's a strange phenomenon with 4 backlashes in zsh.

bash$ echo \\\\
\\

zsh> echo \\\\
\

Do you know why ? Is it a bug ?

Upvotes: 4

Views: 5842

Answers (1)

qqx
qqx

Reputation: 19475

No, this is not a bug. It's just that the echo implementation in these shells have a different default settings for interpretation of backslash sequences.

In either shell the command-line parser will remove one layer of backslashes converting 4 backslashes to 2. That argument is then passed to the echo builtin command. When echo interprets backslash sequences 1 backslash is output for that sequence, if backslash interpretation isn't being done by echo 2 backslashes will be output.

In either shell's implementation of echo the -e or -E option can be used to respectively enable or disable backslash interpretation. So the following will produce the same output in either shell:

echo -e \\\\
echo -E \\\\

Both shells also have shell-level options to alter the default behaviour of their echo command. In zsh the default can be changed with setopt BSD_echo, to change the default in bash the command is shopt -s xpg_echo.

If you're trying to write portable shell scripts, you'd be best served by avoiding use of echo altogether; it is one of the least portable commands around. Use printf instead.

Upvotes: 7

Related Questions