I have found that in bash
echo `echo \\`
output \
\
but
echo `echo \\ `
outputs nothing
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.
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.
– Stéphane Chazelas
Dec 03 '17 at 09:43
$(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 03 '17 at 09:43
\
cmd``) in *sh shells been deprecated?](https://unix.stackexchange.com/q/126927/135943) – Wildcard Dec 04 '17 at 17:05