Defining a variable with or without export

What is export for?

What is the difference between:

export name=value

and

name=value

export makes the variable available to sub-processes.

That is,

export name=value

means that the variable name is available to any process you run from that shell process. If you want a process to make use of this variable, use export , and run the process from that shell.

name=value

means the variable scope is restricted to the shell, and is not available to any other process. You would use this for (say) loop variables, temporary variables etc.

It's important to note that exporting a variable doesn't make it available to parent processes. That is, specifying and exporting a variable in a spawned process doesn't make it available in the process that launched it.


为了说明其他答案的内容:

$ foo="Hello, World"
$ echo $foo
Hello, World
$ bar="Goodbye"
$ export foo
$ bash
bash-3.2$ echo $foo
Hello, World
bash-3.2$ echo $bar

bash-3.2$ 

Others have answered that export makes the variable available to subshells, and that is correct but merely a side effect. When you export a variable, it puts that variable in the environment of the current shell (ie the shell calls putenv(3) or setenv(3)). The environment of a process is inherited across exec, making the variable visible in subshells.

链接地址: http://www.djcxy.com/p/39320.html

上一篇: 如何停止/解决Java应用程序窃取Linux窗口管理器的焦点

下一篇: 用或不用导出定义一个变量