Linux - source a script

From Ever changing code
Jump to navigation Jump to search
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

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