5

I have found that in bash

echo `echo \\`

output \

\

but

echo `echo \\ `

outputs nothing

2

1 Answer 1

8

The documented behaviour of backslashes in backtick-style command substitution is:

When the old-style backquote form of substitution is used, backslash retains its literal meaning except when followed by ‘$’, ‘`’, or ‘\’.

That is, backslashes escape dollar signs, backticks, and other backslashes before the command is given to the shell to process (including before the ordinary processing of backslash escapes and quotes). That means that:

`echo \\ `

is equivalent to

$(echo \ )

and outputs a single space. That single space is inserted as the argument to your outer echo, and then generally lost during field-splitting so just bare echo runs with no arguments.

On the other hand

`echo \\`

leaves a dangling \ at the end of the command, which isn't generally legal (it would indicate line continuation elsewhere), and it's being treated as a literal. Both bash and dash do this, as does tcsh, but zsh doesn't. It doesn't appear to be specified explicitly in POSIX or elsewhere so I suppose that's implementation-defined behaviour.


Using $( ... ) command substitution instead lets you write any script in there without interference. It's almost always going to be better than backtick substitution.

3
  • Note that it's the same as for shell -c 'printf "%s\n" \' (it's better to avoid echo for testing btw as backslash is special to many implementations of echo as well). With bash, it depends on the version. You get the "\" with 4.4, but not 4.3. Dec 3, 2017 at 9:43
  • Would it be more accurate to say that the backslashes escape other backslashes before the usual shell processing of backslashes (and quotes)? Since in the $(echo \ ) case, echo only sees the space due to the backslash escaping it. And Bash's echo doesn't interpret backslashes specially without the -e flag, so it's not the execution of echo that brings the second layer of backslash handling.
    – ilkkachu
    Dec 3, 2017 at 9:43
  • @ilkkachu Yes, that would be more accurate to say, so now it does. Dec 3, 2017 at 9:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.