back ticks vs double quotes
All examples are of variable assignment from command substitution, so they are equivalent. As per Gilles's answer, quoting isn't necessary on right hand of assignment to variable, since word splitting doesn't occur there. So all four are OK.
If they were standalone, i.e. not in assignment, then you'd need to quote. The $(...)
form compared to backticks has advantage that quotes can be nested and broken into multiple lines, which is why this form is generally preferred nowadays. In other words, you can do "$( echo "$var" )"
with this form to protect both the inner expansion of $var
and the outer expansion of $(...)
from word splitting and filename globbing.
As shown in POSIX Shell Command Language specs, embedded multiline scripts don't work with backticks (on the left), but do work with $()
form (on the right).
echo ` echo $(
cat <<\eof cat <<\eof
a here-doc with ` a here-doc with )
eof eof
` )
echo ` echo $(
echo abc # a comment with ` echo abc # a comment with )
` )
echo ` echo $(
echo '`' echo ')'
` )
The four examples are functionally equivalent.
Backticks are obsolete, and unless you are using an 1970 shell like a Bourne shell (like Heirloom) you do not need them. The main problem is that they are quite difficult to nest, try:
$ echo $(uname | $(echo cat))
Linux
$ echo `uname | `echo cat``
bash: command substitution: line 2: syntax error: unexpected end of file
echo cat
On the rigth side of a command line with only an assignement it is not necesary (but harmless) to quote the expansion, as the expansion is considered quoted anyway:
$ var=$(uname)
But that is not always true, an assignment on the command export is regarded as an argument and will be split and glob in some shells (not in bash):
$ dash -c 'export MYVAR=`echo a test`;echo "$MYVAR"'
a
The same reasoning apply to local
(Are quotes needed for local variable assignment?) and declare
(and some other).
What you should do to "fix it", is:
x=$(command -v r2g)
And sometimes (for portable scripts):
export x="$(command -v r2g)"
Yes, the backticks should also be quoted.
This may be a matter of preferred bash style for cases where the command output does not contain spaces. Here's a quote from the author of the shellharden
utility, from "how to do things safely in bash":
Should I use backticks?
Command substitutions also come in this form:
Correct: "`cmd`"
Bad: `cmd`
While it is possible to use this style correctly, it looks even more awkward in quotes and is less readable when nested. The consensus around this one is pretty clear: Avoid.
Shellharden rewrites these into the dollar-parenthesis form.
I also believe it's good form to either quote backticks with "
, or (better) rewrite it to use $()
. If the command output contains spaces or special caracters when using backticks, it may be problematic if not quoting the expression.