Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export variables defined in another file

Tags:

linux

bash

shell

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"
like image 286
philipdotdev Avatar asked Feb 15 '13 22:02

philipdotdev


People also ask

How do I export a variable to another file in JavaScript?

Use named exports to export multiple variables in JavaScript, e.g. export const A = 'a' and export const B = 'b' . The exported variables can be imported by using a named import as import {A, B} from './another-file.

How do you import a variable from another file in react?

To import a variable from another file in React:Export the variable from file A , e.g. export const str = 'hello world' . Import the variable in file B as import {str} from './another-file' .

Can you export environment variables?

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.


1 Answers

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.

like image 137
William Pursell Avatar answered Oct 19 '22 16:10

William Pursell