*export* all variables from key=value file to shel

2019-03-15 00:40发布

问题:

If I want to inherit environment variables to child processes, i do something like:

export MYVAR=tork

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

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.

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.

I tried something like

cat site.conf | while read assignment
do
  export "${assignment}"
done

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).

Is there a way to programmatically export unknown variables in bash?

回答1:

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.

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" 


回答2:

Problem is cat site.conf | while read assignment using pipes.

Pipes create a sub-shell, hence the variable created using export get created in a sub-shell and are not available in your current shell.

You can just do:

source $HOME/site.conf

from your ~/.bashrc to export all the variables and make them available in shell.