当我自定义环境时,我会在文件.bash_profile中添加PATH=$PATH:$My-own-Path
。
教程告诉我应该使用这个:export PATH=$PATH:$My-own-Path
那么这两者有什么区别呢?
当我自定义环境时,我会在文件.bash_profile中添加PATH=$PATH:$My-own-Path
。
教程告诉我应该使用这个:export PATH=$PATH:$My-own-Path
那么这两者有什么区别呢?
回答你具体的问题,在这种情况下,没有任何区别。为什么?
在初始化过程中,变量PATH
已经被导出了。已经导出的变量值的更改不需要另一个export
;这是自动的。随后启动的进程将获得新值。
.bash_profile
。但是假设环境块已设置,有时被视为安全风险。如果有人使用env -i
运行您的脚本会怎样呢? - cdarke.bash_profile
。这个答案特别强调了这种情况。如果“某人”使用env -i
运行我的.bash_profile
,我不认为有任何风险。如果您在这种情况下有具体的安全风险或其他重要问题的实例,请 enlighten 我们。 - Abhayexport
命令将环境变量传递给子进程
来自man bash
:
...
export
和declare -x
命令允许将参数和函数添加到环境中并从中删除。如果修改环境中参数的值,则新值将成为环境的一部分,替换旧值。
同样来自man bash
:
export [-fn] [name[=word]] ... export -p
The supplied names are marked for automatic export to the environment of subsequently executed commands. If the
-f
option is given, the names refer to functions. If no names are given, or if the-p
option is supplied, a list of names of all exported variables is printed. The-n
option causes the export property to be removed from each name. If a variable name is followed by=word
, the value of the variable is set to word.export
returns an exit status of 0 unless an invalid option is encountered, one of the names is not a valid shell variable name, or-f
is supplied with a name that is not a function.
$ myVar=Foo # Create local
$ env | grep '^myVar='
$ export myVar # Export myVar to child process
$ env | grep '^myVar='
Foo
(...)
和其他类似符号运行的子shell:$ thereVar=Bar
$ (echo $thereVar; echo $myVar; $myVar=testing; echo $myVar)
Bar
Foo
Testing
$echo $myVar
Foo
子Shell无法影响父Shell中的变量。
有关子Shell的更多信息,请参考:
每个进程都有一个名为环境块的内存区域。在环境块中有环境变量。这些看起来像普通变量,例如x=42
。
在大多数shell(C shell是一个例外),您可以使用export
将普通变量移动到环境块中。该命令还可以创建环境变量而不经过中间阶段。如果变量已经在环境块中,则export
将没有任何效果。
那么为什么要这样做?当创建新进程时,默认操作是从父进程复制各种“核心信息”到子进程中。这些包括当前目录、umask、文件描述符表、uid和gid以及环境块。
请注意,子进程只会得到父进程环境块的副本。变量不是共享的,也不能通过其他进程间通信机制传递回父进程。
您可以使用env
程序覆盖此默认行为,但这很少需要。
因此,如果我们在shell脚本中使用export
设置环境变量,那么我们创建的所有子进程,在调用其他程序时都会得到它们的副本。一些变量名是众所周知的,并且具有特殊含义,其中PATH
环境变量可能是最重要的。
PATH
环境变量用于在UNIX/Linux上查找程序。每次需要加载程序时,按从左到右的顺序搜索PATH中的目录。Bash还在hash
(KornShell将其称为“跟踪别名”)中缓存可执行路径。
export
和不使用它之间的区别。实际上,在大多数情况下,不会有任何区别。我已经回答了这个问题。 - Abhay