How to export a large list of variables in Bash?
Use set -a
(or the equivalent set -o allexport
) at the top of your file to enable the allexport
shell option. Then use set +a
(or set +o allexport
) at the end of the file (wherever appropriate) to disable the allexport
shell option.
Using enabling the allexport
shell option will have the following effect (from the bash
manual):
Each variable or function that is created or modified is given the export attribute and marked for export to the environment of subsequent commands.
This shell option, set with either set -a
orset -o allexport
, is defined in POSIX (and should therefore be available in all sh
-like shells) as
When this option is on, the export attribute shall be set for each variable to which an assignment is performed; [...] If the assignment precedes a utility name in a command, the export attribute shall not persist in the current execution environment after the utility completes, with the exception that preceding one of the special built-in utilities causes the export attribute to persist after the built-in has completed. If the assignment does not precede a utility name in the command, or if the assignment is a result of the operation of the
getopts
orread
utilities, the export attribute shall persist until the variable is unset.
The variables set while this option is enabled will be exported, i.e. made into environment variables. These environment variables will be available to the current shell environment and to any subsequently created child process environments, as per usual.
This means that you will have to either
- source this file (using
.
, orsource
in shells that have this command), or - start the processes that should have access to the variables from this file.
Here's a hack:
source <(sed 's/^/export /' file.sh)
I assume your shell is like bash and supports process substitutions
Or, edit the file itself:
sed -i 's/[^=]\+/export &; &/' file.sh