Reputation: 401
I have a script that contains a couple of variables that need to be set as an environment variable
The list of variables change constantly and modifying it on my end is not an option. Any idea how I would go about doing it?
sample file foo.sh
FOO="FOOFOO"
BAR="BARBAR"
Upvotes: 16
Views: 8673
Reputation: 212664
There is a difference between a variable and an environment variable. If you execute . foo.sh
and foo.sh
contains the line FOO=value
, then the variable FOO
will be assigned in the current process. It is not an environment variable. To become an environment variable (and thus be available to sub-shells), it must be exported. However, shells provide an option which makes all variable assignments promote the variable to an environment variable, so if you simply do:
set -a
. foo.sh
set +a
then all variable assignments in foo.sh will be made environment variables in the current process. Note that this is not strictly true: in bash, exporting a variable makes it an environement variable in the current shell, but in other shells (dash, for example) exporting the variable does not make it an environment variable in the current shell. (It does cause it to be set it in the environment of subshells, however.) However, in the context of the shell, it does not really matter if a variable is an environment variable in the current process. If it is exported (and therefore set in the environment of any sub-processes), a variable that is not in the environment is functionally equivalent to an environment variable.
Upvotes: 41
Reputation: 7
If you are looking to export only variables with a common prefix, e.g.:
BAZ_FOO="FOOFOO"
BAZ_BAR="BARBAR"
You could simply do this:
. foo.sh
variable_list=()
variable_list=( $(set -o posix ; set |\
grep "BAZ_" |\
cut -d= -f1) )
for variable in "${variable_list[@]}"
do
export "$variable"
done
Upvotes: -1
Reputation: 532418
Are you looking for the '.' command (also spelled 'source' in bash
):
source foo.sh
Since you need to export them to the environment as well, you may need to do a little extra work:
while read -r line; do
export "$line"
done < foo.sh
Upvotes: 11