The command echo $(echo \\\z)
is from the book
, I don’t understand why it outputs
\z
I think it should output
z
The command echo $(echo \\\z)
is from the book
, I don’t understand why it outputs
\z
I think it should output
z
\
is a quoting operator for the shell. When outside other kinds of quotes, \x
is like 'x'
(except when x
is the newline character).
So:
echo \\\x
is like:
echo '\''x'
Or
echo '\x'
So echo
is invoked with two arguments, one that contains echo
(its name) and one that contains \x
.
Per POSIX, the behaviour of echo
when any of its operands (arguments other than the command name) contain a backslash or its first operand is -n
is unspecified. You'll find that the behaviour varies even outside of that.
Per the UNIX specification (with XSI applying at the link above), the behaviour of echo '\z'
is also unspecified as \z
is not one of the standard escape sequences.
With a UNIX compliant echo
, like the echo
builtin of bash -o posix -O xpg_echo
, you can however be guaranteed that:
echo '\\z'
same as:
echo \\\\z
or:
echo \\\\\z
will output \z<newline>
.
Other than that, you won't get any guarantee by POSIX.
Implementation could output z
or \z
or no such escape sequence: \z
or a NUL character...
In practice however, I don't know of any implementation that understands \z
as an escape sequence, so I find that all the ones I tried output \z<newline>
there.
If you want a portable and reliable way to output text, don't use echo
, use printf
instead.
Split the statement echo into sections
\ is the variable bash recognizes as escape
Therefore \ is escaping the character "\" therefore printing \
\z is escaping the character "z" therefore printing z
Taken together, we have \z
echo
won't return anything but its exit status (0 or 1). It outputs\z
in this case, which is different.