Define variable in single line command in Bash

Viewed 9941

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"
2 Answers

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"

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.

Related