Rokas.ma
Rokas.ma

Reputation: 211

bash -c variable does not get assigned

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?

Upvotes: 1

Views: 262

Answers (1)

choroba
choroba

Reputation: 241998

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'

Upvotes: 7

Related Questions