The source command read and execute commands from the filename argument in the current shell context.

When a script is run using source it runs within the existing shell, any variables created or modified by the script will remain available after the script completes. In contrast if the script is run just as filename, then a separate subshell (with a completely separate set of variables) would be spawned to run the script.

Syntax

Syntax for the source command is

source filename [arguments]
. filename [arguments]

source and . (a period) are the same command. If the file is not found in the $PATH, the command will look for the file in the current directory. If the filensme exists, the source command exit code is 0, otherwise, if the file is not found it will return 1.

Example

Commonly source is used to refresh the current shell environment by running the bashrc file. A .bashrc is a script file executed whenever you launch an shell instance. It is defined on a per-user basis and it is located in your home directory.

source .bashrc 

./ and source are not the same.

  • ./script runs the script as an executable file, launching a new shell to run it.
  • source script reads and executes commands from filename in the current shell environment.
  • ./script is not . script, but . script is equivalent to source script

Another usage of source command is to environment variable which are accessible in the shell. In below example, config.sh defines below variables

VAR1="foo"
VAR2="bar"

To access these variables, use the source command to read the configuration file as shown below.

#!/usr/bin/env bash

source config.sh

echo "VAR1 is $VAR1"
echo "VAR2 is $VAR2"