bash – Variable Resolution in Subshell with bash -c

bash

How do I resolve a variable in a subshell inside of "bash -c"?

In the following, the second subshell — the one with an "echo" inside — resolves correctly. The first subshell — with "touch" — does not.

/bin/bash -c "\
A=/tmp/foo; \
echo $( touch \$A;  ); \
echo $( echo in subshell, \$A; ); \
"

Best Answer

It is simply, because the subshell is evaluated from your current shell and not from your subshell. Escaping the $() will make it work as you expected:

/bin/bash -c "\
A=/tmp/foo; \
echo \$( touch \$A;  ); \
echo \$( echo in subshell, \$A; ); \
"
Related Question