In Bash double-quoted strings you can use backslash to make sure the next character is treated as a literal. That is, typing the argument "a\\b"
results in passing the literal string a\b
to the command. From this we can conclude that in both cases you are passing hello\\world
as the final argument to echo
in both cases - each pair of backslashes is expanded to a single literal backslash before passing to echo
.
The -e
flag to echo
"enable[s] interpretation of the following backslash escapes" (see help echo
for details). \\
is listed there as an escape sequence for a single backslash, so in this case echo
is doing the same thing Bash did with the original string and reducing two backslashes to one. The -e
flag is mostly used to be able to include escape sequences like \t
for a horizontal tab character or \n
for a newline. For example:
$ echo -e 'first\tsecond\tthird'
first second third
I would recommend using printf
for this instead. First, its use of a format string means that we can safely mix user-provided strings with escape sequences:
$ printf '%s\t%s\t%s\n' 'inject\nescape' '\\' '\evil'
inject\nescape \\ \evil
Second, not all versions of echo
support -e
, and careless use of unquoted variables will let people change echo
's behaviour:
$ injection='-e a\nb'
$ echo $injection
a
b
Third: This PhD thesis-level analysis.
As a side note, Bash does not treat backslashes in single-quoted strings as escape characters, which is why we get the following results:
$ echo 'hello\\\\world'
hello\\\\world
$ echo -e 'hello\\\\world'
hello\\world
echo
behaves different with-e
, then you are not onUNIX
. The backslach character is always an escape character forecho
on UNIX. – schily Feb 01 '21 at 13:50UNIX
. – schily Feb 01 '21 at 15:49