0

Can anyone explain the differences between `` (back-quotes) and $() in Linux? Thank you very much!

By now , I just found that :

$echo `echo \\\\ `
\
$echo $(echo \\\\ )
\\
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
liu
  • 37
  • 5

2 Answers2

2

It's documented in man bash:

When the old-style backquote form of substitution is used, backslash retains its literal meaning except when followed by $, `, or \. The first backquote not preceded by a backslash terminates the command substitution. When using the $(command) form, all characters between the parentheses make up the command; none are treated specially.

The more important difference is how they nest:

echo $(echo $(echo a))
echo `echo `echo a``   # Wrong
echo `echo \`echo a\``
choroba
  • 231,213
  • 25
  • 204
  • 289
  • A quote, but no source... A quick Google search suggest that the source is the Bash reference manual, but the question is not Bash-specific. Quoting this [section](http://pubs.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_03) of the Shell Command Language specs would be more appropriate, here. – jub0bs Dec 08 '15 at 08:54
1

Back-quotes(``) and $() can be both used for command-substitution, but they have minor difference.

Take the cases mentioned in the question as examples:

$echo `echo \\\\ `

The 1st and 3rd "\" will be treated as escapes, echo \\\\ will be evaluated as "\\"

Therefore, the above command is equal as:

$echo \\

And the first backslash is treated as escape, so the output is:

\

In the case of $(), there is a little tricky, what is evaluated inside $() will be passed as an argument to the outside command.

As an example:

$echo $(echo \\\\ )

What is inside the $() is evaluated as "\\", which is the same as the previous case. What's different is that "\\" will be passed directly to the outside echo command, the first backslash will not be treated as an escape.

Therefore we will got the output:

\\
Hiro Shaw
  • 385
  • 3
  • 18