2

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; ); \
"
2

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; ); \
"
0

Because you are using double quotes, Bash is evaluating the whole string first, then executes it.

Replace your first line with /bin/bash -c echo “\ and you will see the following is the code bash -c is attempting to execute.

/bin/bash -c  echo "\
…


touch \$A;  ); echo $( echo in subshell, \$A; ); "
echo in subshell, \$A; ); "
touch \$A;  ); echo $( echo in subshell, \$A; ); 
touch \$A;  
echo in subshell, \$A; ); 
echo in subshell, \$A; 

Use single quotes instead.

  • I improved the formatting of your answer, however I think it needs your attention as it is unclear what you meant by ... in your explanation. – techraf Apr 7 '16 at 0:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.