Having simple echo commands:
both results in the same output
Can someone please explain me in details how does bash process such a commands (char by char) and why the result is the same in both cases?
The short answer is that
\ is not always special to
bash or to
echo. Double quotes preserve the literal string value of everything inside except
\, and sometimes
!. Outside of double quotes,
\ is always special to bash: it preserves the literal string value of the following character. Inside of quotes, the backslash
\ is only special when followed by one of five characters:
\, or a newline. In the first four cases, it preserves the literal string value of the following character. To the
bash version of echo,
\ is never special unless the
-e flag is provided.
So, in your two cases, what is happening:
in this case,
\ is not followed by one of the five characters mentioned, and so is treated as its literal string value.
in this case, the first
\ is followed by a second
\. The first escapes the second, so that it is interpreted as its literal string value. That is useless here, since it would be interpreted as its literal string value anyway, but it could be useful if you wanted to print a single backslash at the end of a line, like in:
echo "This is a single backslash:\\"
since otherwise the backslash would be interpreted by the shell as escaping
All of this information can be gleaned from the part of the
bash man page about double quotes, found here.
\ preserves the literal string value of the character immediately after it.
So in this case:
\ is preserving the string literal
\ that lies before the
"n". If you were to type in the following...
...you would need to finish the command since the interpreter would not see the
"\" as a string literal but would instead be waiting for user input to escape a "next" character.
However, if the
\ is included inside single quotes, then no escape character is waited for as single quotes, by themselves, preserves the literal character(s) of which they enclose.
So for example:
This would print the backslash as a string literal and not an escape character so the interpreter will not wait for the user to include a character.
This information, and much more, is included in the bash man page.