How do I define a shell script variable to have scope outside of the script How do I define a shell script variable to have scope outside of the script bash bash

How do I define a shell script variable to have scope outside of the script


You can't set variables in parent process's environment. You can only set your current process's environment or prepare an environment for your process's children.

That said, you can instruct your shell to run commands from a script in the current shell process rather than forking a new shell. You can do it like this:

source your_script.sh

or

. your_script.sh

(note the space after the dot). Since here commands inside your_script.sh are run by the current shell the changes made to the environment inside the script are retained.

However, if the shell running your script is not an ancestor of the shell in which you wish to use the environment variable then there is no way to achieve your goal using environment variables at all. For example, if you script is run at initialization by some childless shell all environment settings done there are irreversibly lost forever. In this case, use some other mechanism like a file (perhaps somewhere under /var).

If you want all instances of a given shell to have certain variables set in their environment you can use initialization scripts that most shells use. Usually, they have a system-wide and per-user initialization scripts. For example, bash uses /etc/profile as system-wide initialization script for interactive login shell and $HOME/.bash_profile (also $HOME/.bash_login and $HOME/.profile) as per-user initialization script. See this reference for bash-specific details. If you use a different shell, try its respective manual.


You can't set environment variable for parent process in the child process. What you can do is source script.sh or . script.sh instead of executing it, in this case it's executed in the same bash process and all the changes are preserved.

Also, if you want to have the same variable set in your init script and elsewhere you may put it into /etc/default/something, which is more common. And finally you can source this file into bashrc or /etc/profile.d/something file.