bash -c "v=value; echo $v" displays nothing

Solution 1:

There are two shells involved here:

  • The calling shell, the interactive shell from which you are running this

  • The non-login, non-interactive shell, spawned by bash -c

Now, the problem is, within double quotes the variables are expanded to their respective values, this is true for any shell.

So, as you have used double quotes, the variable expansion, $v, is actually taking place in the calling shell, not the called shell. But the declaration, v=value, is taking place on the called non-interactive shell.

So, in total, you have the variable defined in the called shell and expanded (beforehand) in the calling shell. As the value variable is unset in the calling shell, hence you are getting nothing in the output.

Now, to make the variable definition and expansion to take place in the spawned shell, use single quotes or escape $:

$ bash -c "v=value; echo $v"

$ bash -c 'v=value; echo $v'
value

$ bash -c "v=value; echo \$v"
value

Solution 2:

With double quotes $v gets substituted by the interactive shell. Use single quotes:

$ bash -c 'v=value;echo $v'
value