Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zsh escape backslash

Tags:

zsh

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 ?

like image 520
bruce_ricard Avatar asked Mar 24 '23 01:03

bruce_ricard


1 Answers

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.

like image 133
qqx Avatar answered Apr 07 '23 00:04

qqx