Linux - source a script

From Ever changing code
Revision as of 15:22, 26 February 2016 by Pio2pio (talk | contribs) (Created page with "This is often used to import environment variables to current session. Running the command <code>source</code> on a script executes the script within the context of the curre...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

This is often used to import environment variables to current session.

Running the command source on a script executes the script within the context of the current process. This means that environment variables set by the script remain available after it's finished running. This is in contrast to running a script normally, in which case environment variables set within the newly-spawned process will be lost once the script exits.

You can source any runnable shell script. The end effect will be the same as if you had typed the commands in the script into your terminal. For example, if the script changes directories, when it finishes running, your current working directory will have changed.

source my-script.sh;
. my-script.sh;

Both commands will have the same effect. In contrast, passing the script filename to the desired shell will run the script in a subshell, not the current context.