7

I'm trying to execute a list of commands through the command:

bash -l -c "commands"

However, when I define a variable an then try to use them, the variable is undefined (empty). To be clear:

bash -l -c "var=MyVariable; echo $var"
Surcle
  • 572
  • 1
  • 5
  • 15

2 Answers2

10

Bash expansion (as explained here) will expand the variable value inside the double quotes before actually executing the commands. To avoid so you can follow either of these options:

Option 1:

Avoid the expansion using single quotes

bash -l -c 'var=MyVariable; echo $var'

Option 2:

Avoid the expansion inside the double quotes by escaping the desired variables

bash -l -c "var=MyVariable; echo \$var"

The second option allows you to expand some variables and some others not. For example:

expandVar=MyVariable1
bash -l -c "var=MyVariable; echo $expandVar; echo \$var"
Cristian Ramon-Cortes
  • 1,838
  • 1
  • 19
  • 32
5

Bash expands variables inside double quotes. So in effect in your command $var is replaced by the current value of var before the command is executed. What you want can be accomplished by using single quotes:

bash -l -c 'var=MyVariable; echo $var'

Please note that it is rather unusual to invoke Bash as a login shell (-l) when passing a command string with -c, but then you may have your reasons.

AlexP
  • 4,370
  • 15
  • 15