Linux - source a script

From Ever changing code
Revision as of 00:35, 9 October 2018 by Pio2pio (talk | contribs)
(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.

Excuting versus sourcing a script

When you execute a shell script, the script runs in a new shell. Any changes to the environment caused by the script are scoped to the new shell.

./my-script.sh


When you source a shell script, the script runs in the current shell. Any changes to the environment caused by the script will affect the current shell.

source my-script.sh