Sourcing Scripts

Normally, running a shell script starts a new shell process, often running a different shell than our interactive shell. For example, our login shell may be tcsh or bash, and a script may be run by sh because it starts with '#!/bin/sh -e".

In some circumstances, we might not want a script to be executed by a separate shell process. For example, suppose we just made some changes to our .cshrc or .bashrc file that would affect PATH or some other important environment variable, or the prompt shell variable that describes our shell prompt.

If we run the start up script by typing ~/.cshrc or ~/.bashrc, a new shell process will be started which will execute the commands in the script and then terminate. Commands in the script may alter the shell variables and environment variables of the child process, but the parent process (the process from which you invoked the script), will be unaffected.

In order to make the "current" shell process run the commands in a script, we must source it. This is done using the internal shell command source in all shells except Bourne shell, which uses ".". Bourne shell derivatives support both "." and "source".

Hence, to source .cshrc, we would run

shell-prompt: source ~/.cshrc
        

To source .bashrc, we would run

shell-prompt: source ~/.bashrc
        
or
. ~/.bashrc
        

To source .shrc from a basic Bourne shell, we would have to run

. ~/.shrc
        
Practice

Note

Be sure to thoroughly review the instructions in Section 2, “Practice Problem Instructions” before doing the practice problems below.
  1. What happens when we run a script by simply typing its name at the shell prompt?

  2. How does sourcing a script differ from running it the usual way?

  3. Under what circumstances would we want to source a script rather than run it under a child shell process?