7

I was reading about the echo command in Unix and I got confused in the -e option with the backslash (\) escaped characters I ran the following two examples :

echo "hello\\\\world"

output: hello\\world

now running the same command with the -e :

echo -e "hello\\\\world"

output: hello\world

so what is the meaning of the backslash character with and without the -e option ?

Regards

  • 2
    you really should avoid echo altogether: https://unix.stackexchange.com/questions/65803/why-is-printf-better-than-echo/65819#65819 . I now use almost always printf '%s\n' "something" instead of echo "something" (and benefit from all the other stuff printf provides, %'d, %f, %08d, etc, in addition to the portability benefits and the regularity whatever the content of "something" is, as Stephane Chazelas explains in his post) – Olivier Dulac Feb 01 '21 at 03:45
  • If your echo behaves different with -e, then you are not on UNIX. The backslach character is always an escape character for echo on UNIX. – schily Feb 01 '21 at 13:50
  • @schily, ...agreed as to the first sentence of your above comment, but the second one I'm not so sure of -- XSI extensions are optional, after all. – Charles Duffy Feb 01 '21 at 14:18
  • @CharlesDuffy No, XSI extensions are mandatory if you like to call the beast UNIX. – schily Feb 01 '21 at 15:49

1 Answers1

12

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
l0b0
  • 51,350