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="[email protected]" 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?
You can use the export command to make local variables global. To make your local shell variables global automatically, export them in your . profile file. Note: Variables can be exported down to child shells but not exported up to parent shells.
To export a environment variable you run the export command while setting the variable. We can view a complete list of exported environment variables by running the export command without any arguments. To view all exported variables in the current shell you use the -p flag with export.
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="[email protected]" FULLNAME="Master Yedi"  
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With