0

From what I've read, is it correct to assume that the only thing export does is make the variable visible to child processes?

What would be a scenario where you would want to make a variable only visible to the scope it was initialized in, and what would be a scenario in which you would want a variable available to all child scopes?

2
  • 1
    Scope != process. A shell variable is available to any child scopes within the same process without exporting it. Commented Apr 27, 2016 at 17:16
  • @chepner Gotcha. So I guess how does export come into play then? Commented Apr 27, 2016 at 17:22

1 Answer 1

1

In general, you only need to export a variable that another process will look for in its environment. How do you know which variables those are? You have to read their documentation.

Whether or not a variable is marked for export makes no difference to the current shell.

Let's construct a demonstration.

$ printf 'echo "foo=$foo"\n' > script
$ bash script
foo=
$ foo=3
$ bash script
foo=
$ export foo
bash script
foo=3

The first time and second time you run script, foo is undefined in its environment because its parent process (the current shell) did not export foo. The third time it is called, the parent adds foo to the script's initial environment because foo was exported.


In response to your comment, the term "environment" has a very precise meaning here. All processes, not just shells, receive an array of strings from its parent on startup, referred to as its environment. There are no particular semantics associated with these strings; it's up to the receiving program how to interpret them.

The shell, for example, ignores strings in its environment that do not have the form name=value, where name is a valid shell identifier. For each such string, the shell defines a shell variable with the given name and value, and marks its export attribute. This is what we mean by an environment variable. You can also "promote" a regular shell variable at any time to an environment variable using the export command, but this doesn't affect the meaning of the variable in the current process.

When any process creates a new process, a copy of its environment is given to the new process. The shell additionally creates name=value strings to pass on from each of its environment variables.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! This is starting to make more sense. I'm still having a hard time grasping the difference between a shell and an environment. When I open terminal on osx, am I opening a new environment?
I would not say "another program", because only child processes can have access to exported variables, while arbitrary other programs certainly don´t.
@Harald Thanks. I caught myself typing "program" many times where I meant to say "process"; that one slipped by.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.