0

I'm trying to understand this behavior:

bash-5.1$ echo `echo \\\\\\\z`
\\z

For the inner echo command, 1st escape character (\) would escape the leading escape character (2nd one), and it repeats with 3rd escaping 4rth, and 5th escaping 6th. Shouldn't the 7th escape character escape the leading z character, leading to \\\z which under the influence of outer echo would lead to \z as the answer?

NOTE : - If the last \ will not escape the z (which could be the possible case as I'm assuming from seeing the answer), then why is that?

that other guy
  • 116,971
  • 11
  • 170
  • 194
Tanish
  • 35
  • 4
  • 1
    My shell outputs `\\\z`. It's not clear what you're talking about in regards to "inner" and "outer" echo here or which "above bash related question" you're referring to. – user229044 Oct 04 '21 at 03:44
  • Bash outputs `\\z` on my system and the "above bash related question" refers to the title, which has an outer and inner echo via command substitution: ``echo `echo \\\\\\\z` ``. I clarified and nominated for reopen. – that other guy Oct 04 '21 at 06:36

1 Answers1

1

How does echo `echo \\\\\\\z` result in \\z?

Syntax tree looks like this:

- echo -> ` -> echo -> \\\\\\\z

We start from \\\\\\\z. Firstly https://www.gnu.org/software/bash/manual/html_node/Escape-Character.html#Escape-Character happens:

A non-quoted backslash ‘\’ is the Bash escape character. It preserves the literal value of the next character that follows [...]

The \\\\\\z is unquoted, so we transform each pair \? to ?, like \\ into \ and \z into z.

\\\\\\\z
^^|||||| -> \
  ^^|||| -> \
    ^^|| -> \
      ^^ -> z

- echo -> ` -> echo -> \\\z

Then `...` backquotes happen, one of the reasons why $(..) is preferred for command substitution. From https://www.gnu.org/software/bash/manual/html_node/Command-Substitution.html#Command-Substitution :

When the old-style backquote form of substitution is used, backslash retains its literal meaning except when followed by ‘$’, ‘`’, or ‘\’.

In \\\z the first \ is followed by \, so it's meaning is not literal. The meaning of the first \ is, as in the previous point, it preserves the literal value of the next character. So, basically, \\ is replaced by a single \. The rest \z is preserved literally.

\\\z
^^    -> \
  ..  -> \z

- echo -> ` -> echo -> \\z

Then echo '\\z' is executed, and it outputs \\z and the command substitution `...` is replaced by the output of the command inside, so, well, by \\z.

- echo -> \\z

Then echo '\\z' once again outputs \\z.

KamilCuk
  • 120,984
  • 8
  • 59
  • 111