Bash Command Substitution and Double Quotes – Why Results Differ

bashcommand-substitutionshell

Here is an example where backticks and $() behave differently:

$ echo "$(echo \"test\")"
"test"
$ echo "`echo \"test\"`"
test

My understanding was this is because "backslashes (\) inside backticks are handled in a non-obvious manner"

But it seems like this is something else because when I remove outer double quotes the results became similar:

$ echo $(echo \"test\")
"test"
$ echo `echo \"test\"`
"test"

Could someone explain me how it works and why "`echo \"test\"`" removes double quotes?

Best Answer

You are right, it is something else in this case.

The solution is still in the same link, but the second point:

  • Nested quoting inside $() is far more convenient.

    [...]

    `...` requires backslashes around the internal quotes in order to be portable.

Thus,

echo "`echo \"test\"`"

does not equal this:

echo "$(echo \"test\")"

but this:

echo "$(echo "test")"

You need to compare it instead with this:

echo "`echo \\"test\\"`"
Related Question