Export variables defined in another file

后端 未结 3 1171
遇见更好的自我
遇见更好的自我 2020-12-30 04:58

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

相关标签:
3条回答
  • 2020-12-30 05:13

    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.

    0 讨论(0)
  • 2020-12-30 05:19

    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
    
    0 讨论(0)
  • 2020-12-30 05:31

    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
    
    0 讨论(0)
提交回复
热议问题