Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define variable in single line command in Bash [duplicate]

Tags:

bash

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"
like image 642
Surcle Avatar asked Nov 09 '17 12:11

Surcle


People also ask

How do you pass variables in single quotes in bash?

If the backslash ( \ ) is used before the single quote then the value of the variable will be printed with single quote.

How do you declare a variable in a bash script?

A variable in bash is created by assigning a value to its reference. Although the built-in declare statement does not need to be used to explicitly declare a variable in bash, the command is often employed for more advanced variable management tasks.

What is $1 and $2 in bash?

$0 is the name of the script itself (script.sh) $1 is the first argument (filename1) $2 is the second argument (dir1)

What does $_ mean in bash?

$_ (dollar underscore) is another special bash parameter and used to reference the absolute file name of the shell or bash script which is being executed as specified in the argument list. This bash parameter is also used to hold the name of mail file while checking emails. $@


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"
like image 67
Cristian Ramon-Cortes Avatar answered Oct 16 '22 07:10

Cristian Ramon-Cortes


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.

like image 35
AlexP Avatar answered Oct 16 '22 08:10

AlexP