0
votes

I am trying to execute the following command:

 $ bash -c "var='test' && echo $var"

and only an empty line is being printed.

If I execute the same command without bash -c

$ var='test' && echo $var 
test

the value assigned to $var is being printed. Could someone explain why I can't assign variables in the first example?

1
Just single quote it like bash -c 'var='test' && echo $var' and also try to run var=foobar;bash -c "var='test' && echo $var" you will understand what is happening - P....

1 Answers

6
votes

Double quotes expand variables, so your command is expanded to

bash -c "var='test' && echo"

if $var is empty when you run it. You can verify the behaviour with

var=hey
bash -c "var='test' && echo $var"

Switch the quotes:

bash -c 'var="test" && echo $var'