59

I've seen shell scripts that include a line such as:

source someOtherFile

I know that causes the content of someOtherFile to execute, but what is the significance of source?


Follow-up questions: Can ANY script be sourced, or only certain type of scripts? Are there any side-effects other than environment variables when a script is sourced (as opposed to normally executing it)?

Mogsdad
  • 44,709
  • 21
  • 151
  • 275
Shailesh Tainwala
  • 6,299
  • 12
  • 58
  • 69
  • 2
    cross site duplicate: http://superuser.com/questions/176783/what-is-the-difference-between-executing-a-bash-script-and-sourcing-a-bash-scrip/176788#176788 – Lesmana Jul 30 '14 at 10:10

3 Answers3

67

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.

Interrobang
  • 16,984
  • 3
  • 55
  • 63
  • 2
    Can ANY script be sourced, or only certain type of scripts? Any side-effects other than environment variables when a script is sourced (as opposed to normally executing it)? Also, your answer is succinct and understandable. Thanks! – Shailesh Tainwala Feb 17 '12 at 13:14
  • 4
    You can source any shell script. Side effects are created by the fact that the script is literally running in your process. So if it changes directories, you'll see your pwd change. Whereas just executing a shell script normally won't change your pwd. – Interrobang Feb 17 '12 at 18:28
  • What about is i have a long running script inside the file to source? is it going to finished ? or is there a default timeout of it.? – ji-ruh Dec 14 '16 at 15:26
16

If you tell the shell, e.g. bash, to read a file and execute the commands in the file, it's called sourcing. The main point is, the current process (shell) does this, not a new child process.

In BASH you can use the source command or simply . to source a file.

Mithrandir
  • 24,869
  • 6
  • 50
  • 66
2

source is a Unix command that evaluates the file following the command, as a list of commands, executed in the current context. You can also use . for sourcing the file.

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.

Pratik Patil
  • 3,662
  • 3
  • 31
  • 31