Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

Bash seems to differentiate between variables which have been exported and those which have not.

example:

$ FOO=BAR
$ env | grep FOO
$ set | grep FOO
FOO=BAR

set sees the variable but env does not.

$ export BAR=FOO
$ env | grep FOO
BAR=FOO
$ set | grep FOO
BAR=FOO
FOO=BAR

set sees both variables but env sees only the exported variable.

I know that set is a bash builtin and env is not.

What are the differences between variables which are exported and those which are not?

share|improve this question
5  
Terminology note: an “environment variable” is always exported. A non-exported variable is a “shell variable” (or “parameter”). –  Gilles Sep 13 '12 at 0:28
add comment

1 Answer

up vote 18 down vote accepted

Exported variables are carried into the environment of processes started by the shell that exported them, while non-exported variables are local to the current process only. From the export man page:

The shell shall give the export attribute to the variables corresponding to the specified names, which shall cause them to be in the environment of subsequently executed commands.

set outputs the current environment, which includes any local non-exported variables. env is used to launch programs in a new environment, and with no arguments will output what that new environment would be. Since env is creating a new environment, only exported variables are brought through, as is the case for any program launched from that shell. For example, spawning a second shell within the first (I used $$ to represent prompts in the inner shell):

$ FOO=BAR
$ bash
$$ echo $FOO
$$ exit
$ export FOO
$ bash
$$ echo $FOO
BAR
$$

Edited to show that it's the variable itself that's exported, not the value. Once you export foo, foo becomes a global variable and shows up in subsequent environments, even if changed later:

$ export FOO
$ FOO=BAR
$ bash
$$ echo $FOO
BAR
$$
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.