25

我要写一个脚本,看起来没有区别:

export k=1

k=1

我对吗?

4

3 回答 3

42

export使变量可用于子进程。

也就是说,如果您从脚本中生成一个新进程,则该变量k将不可用于该子进程,除非您使用export它。请注意,如果您在子流程中更改此变量,则该更改在父流程中将不可见。

有关更多详细信息,请参阅本文档的第 3.2.3 节。

于 2012-09-24T08:53:30.857 回答
24

我创建了一个简单的脚本来显示差异:

$ cat script.sh 
echo $answer

让我们测试一下export

$ answer=42
$ ./script.sh 

$ . script.sh 
42

仅当使用相同的进程执行脚本时才知道该值(即,相同的bash实例,使用source/ .

现在,使用export

$ export answer=42
$ ./script.sh 
42
$ . script.sh 
42

该值是子进程已知的。

因此,如果您希望子进程知道变量的值,那么您应该使用export.

于 2012-09-24T09:01:31.640 回答
15

每个进程,甚至在 Windows 上,都有一个称为环境块的内存块,其中包含环境变量。创建新进程时,默认情况下会将父进程的环境块复制到子进程,因此环境变量是一种将文本数据传递给子进程的简单方法。

The export command creates an environment variable, or converts an ordinary local variable into an environment variable. In the C-shell, one of its few redeeming features is that it uses a different syntax for environment variables (setenv) to local variables (set). Bourne shell derivatives, like Bash and Korn shell, hide all that.

Currently, only simple values can be passed, so items like arrays are not supported (it just exports the first element). Variable attributes, set using define, are also not exported unless the child process is a shell of the same type, i.e. another instance of bash. This also applies to exported functions, although it is possible to sometimes hack this between shells of different types (using eval).

在 Bash(和其他)中,有一个名为的 shell 设置allexport,这意味着所有变量都是环境变量——一般来说可能是个坏主意。您可以提供与 C 等语言不同的环境块 using execve,但在 shell 中您需要类似 的程序env,详情请参阅man env

于 2012-09-24T10:04:58.340 回答