Could some one explain what is happening behind the scenes in character escaping in Linux shell? I tried the following and googled a lot, without any success in understanding what (and how) is going on:
root@sv01:~# echo -e "\ Hello!"
\ Hello!
root@sv01:~# echo -e "\\ Hello!"
\ Hello!
root@sv01:~# echo -e "\\\ Hello!"
\ Hello!
root@sv01:~# echo -e "\\\\ Hello!"
\ Hello!
root@sv01:~# echo -e "\\\\\ Hello!"
\\ Hello!
root@sv01:~# echo -e "\\\\\\ Hello!"
\\ Hello!
root@sv01:~# echo -e "\\\\\\\ Hello!"
\\ Hello!
root@sv01:~# echo -e "\\\\\\\\ Hello!"
\\ Hello!
root@sv01:~# echo -e "\\\\\\\\\ Hello!"
\\\ Hello!
root@sv01:~# echo -e "\n Hello!"
Hello!
root@sv01:~# echo -e "\\n Hello!"
Hello!
root@sv01:~# echo -e "\\\n Hello!"
\n Hello!
I am totally lost there, so for example, why do three backslashes give only one back slash? I would expect: the first two will be escaped to one, the third one will find nothing to escape so it will remain a slash (line in the first experiment), but what is happening is that the third one is just disappears.
Why I am getting one backslash from four \\\\ Hello
? I would expect each pair will give one back slash -> two backslashes.
And why I need three backslashes in the last case to get \n escaped? what is happening in background of escaping to get that? and how is it different from \\n
case?
I appreciate any explanation of what is going on in the previous lines.
echo -e
behavior is not standards-defined anyhow -- see pubs.opengroup.org/onlinepubs/9699919799/utilities/echo.html. Output is completely implementation-defined if there's a literal backslash anywhere in the inputs, and the only allowed option is-n
(meaning that a standards-compliant implementation will haveecho -e
print-e
on its output).echo -e
isn't safe:echo
will behave in accordance with the standard if bothposix
andxpg_echo
runtime options are enabled, or if compiled with equivalent build-time options. The safe practice is to useprintf
instead -- see the APPLICATION USAGE and RATIONALE sections of the above link describing how to makeprintf
act as a replacement forecho
.