2

Say my bash shell have the following environment variable:

export a="Hello World"

If I executed a process from the bash shell, the a environment variable will be inherited by this child process.

My question is: will a be inherited by the child process as an environment variable or as a shell variable, that is, will a in the child process be exported?

2 Answers 2

4

As an environment variable.

This means that any child process that the child process starts will inherit the variable as well.

Testing:

$ export FOO=bar
$ sh
$ sh
$ sh
$ echo "$FOO"
bar
$ exit
$ exit
$ exit

Above, the shell creating the environment variable FOO started a new interactive shell. That started another one, and that one started another one. Within this great-grandchild shell, $FOO has the value bar.

Another test showing that if if a subshell changes the environment variable, the change is carried over into later subshells (but is not propagated to the parent shells):

$ export FOO=bar
$ ( ( echo "$FOO"; FOO=quux; ( ( ( echo "$FOO" ) ) ) ) )
bar
quux
$ echo "$FOO"
bar

(in this example, it doesn't matter that FOO is exported as ( ... ) subshells also inherit shell variables, but the the effect would have been the same had each ( ... ) been a totally separate process)

Note that environment variables are available to any process started from the shell, not just shell scripts. It would not make sense for a C program or awk script to inherit them as shell variables as there is no concept of these kinds of variables in those languages (environment variables are strictly key-value pairs, whereas shell variables may be typed as integers, read-only, arrays, associative arrays, etc., depending on the capabilities of the shell).

1

You can read your process environmental variables from /proc/PID/environ. So when you export variable, it is stated in this /proc "file".

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .