Shell variables vs. environment variables
MY_HOME="/home/my_user" sets the shell variable called
MY_HOME. Shells are programming languages, and have variables (also called parameters). After this assignment, you can use the value of the
variable, e.g. with
Shell variables are an internal shell concept. When that shell instance terminates,
MY_HOME is forgotten. What every program knows about and transmits to its children is environment variables.
Inside the shell, environment variables and shell variables work in very similar ways. What actually happens is that all environment variables that the shell inherits from its parent become shell variables. Conversely, a shell variable that is defined in a shell script will become an environment variable if you export it.
More details you can skip on first reading
The reason why shell variables don't automatically become environment variables is partly that a script might accidentally use a variable name that's meaningful to a program that it launches, and partly just historical.
Some very old shells required
export to be used each time you changed a variable name, but all modern shells keep track of assignments for environment variables, so that the following snippet echoes
env | grep '^myvar='
Also, some very old shells required separate commands for
export myvar, but all modern shells understand
You can run
set -a to make all shell variable assignments automatically export the variable, so that
myvar=foo is equivalent to
export myvar=foo if you ran
set -a in that shell first.
Quoting is mostly orthogonal. If the value you're assigning to the variable doesn't contain any characters that are special to the shell, you don't need any quotes. If there are special characters, you need to protect them with single quotes or double quotes or backslashes or a combination thereof. This goes for both the plain
myvar=value syntax and the
There is one difference between the assignment syntax and the
export syntax. The shell expands the results of variable substitutions
$foo further, performing field (word) splitting and pathname expansion (globbing). This means that if the value of
hello *, then
echo $myvar prints
hello followed by a single space followed by the list of files in the current directory. This is almost never desirable, hence the general principle to always use double quotes around variable substitutions (unless you know that you need pathname expansion or field splitting):
echo "$myvar". In the case of a simple assignment,
othervar=$myvar in fact reliably copies the value of
othervar, because globbing and word splitting are inhibited in assignments (because they create multiple words, but a single word is expected). This dispensation does not apply to
export, however. So if you want to remember a simple rule, just always use double quotes around variable substitutions.