vkapustin vkapustin - 5 months ago 6x
Bash Question

In bash, when creating Variables. When to export and when not to export?

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?


In general, you only need to export a variable that another program 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=3
$ bash script
$ export foo
bash script

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.