6

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
  • 552
  • 4
  • 15

2 Answers2

9

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,758
  • 1
  • 20
  • 29
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,230
  • 13
  • 13