Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why must I enter "\\\0" to create a string "\0" in zsh?

> echo 0
0
> echo \0
0
slu@dev:~
> echo \\0

slu@dev:~    
> echo "\\0"
                   # <--- What!!?
slu@dev:~
> echo \\\0

slu@dev:~
> echo "\\\0"
\0
slu@dev:~
> bash
Executing .bashrc
$ echo "\0"
\0
$ echo "\\0"
\0
$ echo "\\\0"
\\0

I gotta say, bash's behavior makes a lot more sense to me.

More details:

slu@dev:~
> echo "0" | hexdump -C
00000000  30 0a                                             |0.|
00000002
slu@dev:~
> echo "\0" | hexdump -C
00000000  00 0a                                             |..|
00000002
slu@dev:~
> echo "\\0" | hexdump -C
00000000  00 0a                                             |..|
00000002
slu@dev:~
> echo "\\\0" | hexdump -C
00000000  5c 30 0a                                          |\0.|
00000003
slu@dev:~
> echo "\\\\0" | hexdump -C
00000000  5c 30 0a                                          |\0.|
00000003
slu@dev:~
> echo "\\\\\0" | hexdump -C
00000000  5c 00 0a                                          |\..|
00000003
slu@dev:~
> echo "\\\\\\0" | hexdump -C
00000000  5c 00 0a                                          |\..|
00000003
slu@dev:~
> echo "\\\\\\\0" | hexdump -C
00000000  5c 5c 30 0a                                       |\\0.|
00000004

The biggest issue is that there is no value that produces the desired result \0 on both bash and zsh.

Update:

slu@dev:~
> echo '0' | hexdump -C
00000000  30 0a                                             |0.|
00000002
slu@dev:~
> echo '\' | hexdump -C
00000000  5c 0a                                             |\.|
00000002
slu@dev:~
> echo '\\' | hexdump -C
00000000  5c 0a                                             |\.|
00000002
slu@dev:~
> echo \\ | hexdump -C
00000000  5c 0a                                             |\.|
00000002
slu@dev:~
> echo '\\0' | hexdump -C
00000000  5c 30 0a                                          |\0.|
00000003

Looks like using single quotes helps get consistent behavior. I'd love for somebody to explain the behavior with the double-quotes.

like image 413
Steven Lu Avatar asked Apr 12 '13 21:04

Steven Lu


1 Answers

Use single quotes and turn off escape handling in echo with the -E flag.

echo -E '\0' should produce a \0 on both zsh and bash (and dash).

like image 158
Mark Harviston Avatar answered Sep 30 '22 03:09

Mark Harviston