*将所有变量从键=值文件导出到外壳 [英] *export* all variables from key=value file to shell
问题描述
如果我想将环境变量继承给子进程,请执行以下操作:
If I want to inherit environment variables to child processes, i do something like:
export MYVAR=tork
假设我有一个文件site.conf
,其中包含变量的值分配(可以包含空格):
Assume I have a a file site.conf
containing assignments of values (that can contain spaces) to variables:
EMAIL="dev@example.com"
FULLNAME="Master Yedi"
FOO=bar
现在,我想在每次打开新的外壳程序时都处理该文件(例如,使用~/.bashrc
或~/.profile
中的某些代码),以便从该新打开的外壳程序中启动的任何进程都将通过环境变量继承赋值
Now I would like to process this file whenever I open a new shell (e.g. with some code in ~/.bashrc
or ~/.profile
), so that any processes started from within that newly opened shell will inherit the assignments via environmental variables.
一个明显的解决方案是在site.conf
中的每一行前面加上一个export
,然后仅提供文件源.但是我无法执行此操作,因为其他一些应用程序也可以(直接)读取该文件,因此格式是固定的.
The obvious solution would be to prefix each line in site.conf
with an export
and just source the file. However I cannot do this since the file is also read (directly) by some other applications, so the format is fixed.
我尝试过类似的事情
cat site.conf | while read assignment
do
export "${assignment}"
done
但是由于种种原因,这是行不通的(最重要的是export
是在子shell中执行的,因此该变量将永远不会导出到调用shell的子级中).
But this doesn't work, for various reasons (the most important being that export
is executed in a subshell, so the variable will never be exported to the children of the calling shell).
有没有办法在bash中以编程方式export
未知变量?
Is there a way to programmatically export
unknown variables in bash?
推荐答案
在获取文件之前运行set -a
.这会标记所有随后自动导出的新变量和修改过的变量.
Run set -a
before sourcing the file. This marks all new and modified variables that follow for export automatically.
set -a
source site.conf
set +a # Require export again, if desired.
您观察到的问题是管道在子Shell中执行export
.您可以简单地通过使用输入重定向而不是管道来避免这种情况.
The problem you observed is that the pipe executes the export
in a subshell. You can avoid that simply by using input redirection instead of a pipe.
while read assignment; do
export "$assignment"
done < site.conf
这行不通,但是,如果(虽然不太可能)您在一行上有多个分配,例如
This won't work, however, if (unlikely though it is) you have multiple assignments on one line, such as
EMAIL="dev@example.com" FULLNAME="Master Yedi"
这篇关于*将所有变量从键=值文件导出到外壳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!