2

The command echo $(echo \\\z) is from the book , I don’t understand why it outputs

\z

I think it should output

z

3
  • As you've referenced tldp bash guide as "the book," I feel I should tell you that it is out of date and contains deprecated advice now widely considered bad practice. I recommend the Wooledge Bash Wiki instead. Plus this site, U&L Stack Exchange. (I have some key links in my profile.)
    – Wildcard
    Nov 30, 2017 at 23:57
  • Minor nitpick: the command echo won't return anything but its exit status (0 or 1). It outputs \z in this case, which is different.
    – Wildcard
    Dec 1, 2017 at 0:08
  • @Wildcard Yes, I have replaced ‘return’ with ‘output’.
    – tmpbin
    Dec 1, 2017 at 0:24

2 Answers 2

6

\ 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.

2

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .