0

Title. echo "\*" has the exact same output as echo "\\*", \*. I am using GNU bash 5.2.15.

I expected echo "\\*" to output \*, but I do not know why echo "\*" did too. To my knowledge it should have gone a bit like this:

  1. Bash sees: $echo "\*"
  2. Bash processes double quotes, leaving the backslash unescaped: $echo \*
  3. Bash escapes * with backslash: $echo *
  4. Bash prints *.

My suspicion lies in 3. I believe that the backslash does not escape the * because it is already escaped in 2. Is this correct?

7
  • gnu.org/software/bash/manual/bash.html#Quote-Removal Commented Feb 8, 2023 at 8:12
  • @muru I have read this. I still don't understand why the \ does not disappear, escaping the *. Commented Feb 8, 2023 at 8:36
  • It says that \ is removed only if it was unquoted. In this case it is quoted, so it won't be removed. Commented Feb 8, 2023 at 8:44
  • 1
    What are the $ symbols on the front of echo? If they're a prompt then your shell won't see that - it printed it for you Commented Feb 8, 2023 at 8:56
  • What about Why does the command echo echo \\\z output \z? Commented Feb 8, 2023 at 9:00

2 Answers 2

1

\ remains as \ if there is no unescaping that happens.

From the Double Quotes section of Bash's manual:

Backslashes preceding characters without a special meaning are left unmodified.

So "\*" which has no occurring transformation is the same as "\\*" where \\ is unescaped as \. The echo command also doesn't transform anything as it would produce the same output as printf %s.

0

Yes indeed, the double quotes escape the wildcards *.

Because the * has no meaning within double-quotes, the backslash cannot escape it.

When processing backslashes, bash checks if the following character has a special meaning in the current state. If yes, the backslash will not be printed and the next character will be escaped. If no, the backslash will simply be printed.

So in case "\*", the first backslash protects a * which doesn't need to be escaped in this double-quoted context so it will simply be printed.

But in case "\\*", the first backslash protects a backslash which can have special meaning in a double-quoted context, so it will be escaped by the first backslash. This means the second backslash will be printed.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.