Linux Source Command: How to Import Variables

This article provides an overview of the source command in the Linux operating system, explaining how it enables the current shell session to read, execute, and import variables from external files. By reading this guide, you will learn the core mechanics of the source command, why it differs from normal script execution, and how to effectively use it to maintain persistent configuration and environment variables across your shell workflows.


The Challenge of Variable Persistence in Bash

When you execute a shell script using standard invocation methods—such as ./script.sh or bash script.sh—the operating system spawns a new, separate child process (a subshell).

Any variables declared, modified, or exported inside that script exist only within the lifetime of that child process. Once the script finishes executing, the subshell terminates, and its memory space is destroyed. Consequently, any variables defined inside the file are not inherited by the parent shell where the command was initiated.

The Role of the source Command

The source command (represented alternatively by a single dot .) is a shell built-in command in Bash and other POSIX-compliant shells. Its primary role is to execute commands from a specified file directly within the current shell environment, rather than launching a subshell.

When you use source to read a file containing variable definitions, the shell interprets the lines as if you had typed them directly into your current terminal prompt. As a result, all variables defined in that file remain active and accessible in your existing session.

Basic Syntax and Usage

The syntax for the command is straightforward:

source /path/to/filename

Or using the POSIX-compliant dot operator:

. /path/to/filename

Example Scenario

Consider a configuration file named config.env:

# config.env
DB_HOST="localhost"
DB_PORT="5432"
API_KEY="xyz12345"

If you execute this file directly:

bash config.env
echo $DB_HOST

The output will be blank because $DB_HOST was created and destroyed in a subshell.

If you import the variables using source:

source config.env
echo $DB_HOST

The output will immediately return:

localhost

Key Technical Differences: Execution vs. Sourcing

  1. Process Context: Standard execution forks a child process; source runs within the existing process space.
  2. File Permissions: To run a script normally, it must have execute permissions (chmod +x). To source a file, the user only requires read permissions (r), because the active shell process is simply reading and evaluating text lines from the target file.
  3. Shell History and State: Modifying functions, aliases, and working directories (cd) inside a sourced file alters the state of your active shell, whereas executing the script leaves the current shell untouched.

Common Use Cases