Get 50% Discount Offer 26 Days

Recommended Services
Supported Scripts
WordPress
Hubspot
Joomla
Drupal
Wix
Shopify
Magento
Typeo3
What Is the Linux source Command and How to Use It?

The linux source command is one of the most essential tools for anyone who finds him or herself generally interacting and working with shell scripts. It is particularly helpful for those who are either new to the shell or those who are familiar with the commands but can also help the shell to read and execute scripts of the current session. From here, it goes step-by-step through general usage and more specific approaches, ensuring that you understand them completely and know how they work. By the end, you will know how to utilize the source to optimize your environment configuration and shell scripting.

1. What is the source Command in Linux?

The source command is a built-in shell utility used to read and execute the content of a script or file in the current shell session. Unlike executing a script by directly using ./filename, Source runs the file without creating a new shell instance. It is perfect to load environment variables in the current session. It also allows you to define any variables, functions, or configurations in the sourced file that will directly affect the current session. For people managing scripts & configurations in linux, the command is essential.

Basic Syntax

source filename

A shorthand for source is the dot (.) command:

. filename

2. When to Use Linux Source Command

The use of ‘source‘ can enhance your shell scripting habits. The linux source command is quite useful each time you want to run settings or variables in the current shell without having to start a new shell session.

  • Loading or updating environment variables.
  • Applying changes to configuration files without restarting the terminal.
  • Defining and using shell functions across scripts or interactive sessions.

Typical Scenarios

  1. Sourcing environment variables for a project.
  2. Reloading changes in .bashrc or .bash_profile without needing to restart the shell.
  3. Bringing functions from one script into another for modular code development.

These scenarios highlight why the source command is a staple in Linux workflows.

3. Practical Examples of Using Source

Example 1: Loading Environment Variables

Suppose you have a script named env_vars.sh that holds important environment variable definitions for your project. This file might look like this:

export PATH_TO_PROJECT=/home/user/project
export DATABASE_URL=localhost:5432
export MODE=development
loading environment variables from env_vars.sh using the source command

These export statements assign values to variables and make them accessible to any subsequent command run in the shell session. To load these variables into your current shell environment without restarting or affecting other processes, use the source command:

source env_vars.sh
Using the source command to load variables from env_vars.sh in the shell

After running this command, $PATH_TO_PROJECT, $DATABASE_URL, and $MODE will be recognized by the current shell session, making it easier to manage project-specific settings.

Verification

echo $PATH_TO_PROJECT  # Outputs: /home/user/project
Verifying environment variable PATH_TO_PROJECT with echo command output
echo $DATABASE_URL 
Echoing DATABASE_URL variable to display localhost:5432 output.
echo $MODE             # Outputs: development
Echoing MODE variable to display development environment output

Example 2: Reloading .bashrc or .bash_profile

Modifying .bashrc or .bash_profile files adds new aliases, functions, or environment variables. These changes only take effect after a session restart or when the file is re-sourced:

source ~/.bashrc
Reloading .bashrc file to apply changes using the source command

Save this command as a fast way to get your current shell to use new changes without rebooting the terminal, as this command loads the updated file.

Example 3: Importing Shell Functions

Suppose you have a file helper.sh containing useful shell functions:

log_info() {
    echo "[INFO]: $1"
}

calculate() {
    echo "$(($1 * $2))"
}

To use these functions in a current session or another script:

source helpers.sh
Using source command to load functions from helpers.sh into the session

You can then call log_info or calculate directly:

log_info "Script started"  # Outputs: [INFO]: Script started
Calling log_info function to output Script started message
calculate 5 3              # Outputs: 15
Using calculate function with inputs 5 and 3 to output result 15

4. How source Differs from Executing a Script Directly

A common question is how the Linux source Command differs from executing a script using ./filename. When you execute a script directly, it runs in a subshell, meaning that any variables or changes made in the script do not impact the parent shell.

Example

Consider a script named script.sh that defines an environment variable:

export MY_VAR="Hello World"
Example of defining MY_VAR environment variable in script.sh for sourcing

If you run:

./script.sh
echo $MY_VAR  # No output, as MY_VAR is not set in the current shell
Running script.sh directly; MY_VAR is not set in the current shell

It will not yield any output since ./script.sh runs in a subshell, meaning the variable MY_VAR is only available during the script’s execution and not beyond it.

However, when you run:

source script.sh
echo $MY_VAR  # Outputs: Hello World
Using source on script.sh MY_VAR is set in current shell as Hello World

The script runs within the current shell environment session by the source command but only in the environment of that same session. This process will keep variables as they exist and can be referenced afterward.

5. Troubleshooting Common Issues with source

While the Linux source Command is simple to use, some common problems can arise when using it. One such issue is receiving a No such file or directory error. An error typically happens if the script path is incorrect or the file doesn’t have the correct permissions. To prevent this, double-check that the file exists and has the necessary read permissions.

Solution

Check the correct path is used or switch to the directory containing the script before running:

cd /path/to/directory
source script.sh

Syntax Errors

If the script has syntax errors, the Linux source Command will stop running when it faces an error. To catch issues before sourcing, use:

bash -n script.sh
Checking script.sh for syntax errors with bash -n before sourcing

This feature will scan the file for syntax issues without executing it.

6. Practical Tips for Working with Source

Tip 1: Store Reusable Scripts in a Dedicated Directory

Keep configuration and reusable scripts organized in a dedicated directory such as ~/scripts. This approach simplifies sourcing, as you can use absolute paths or maintain a logical file structure.

Example:

source ~/scripts/setup.sh

Tip 2: Create Initialization Files for Projects

For custom setups available on a per-project basis, you will create a script called project_init.sh and load environment variables, change directories, or set up shell functions. It can save you some time.

Example project_init.sh:

#!/bin/bash
export PROJECT_HOME=~/projects/my_app
cd $PROJECT_HOME
echo "Project environment loaded for $PROJECT_HOME"
Example project_init.sh to set PROJECT_HOME and load project environment

To use it:

source project_init.sh
Using source to load project_init.sh and set project environment path

7. Advanced Usage of source

Example 1: Conditional Sourcing

Before sourcing a file, you can include conditional checks to reduce errors that occur. Employing this technique affords extra assurance to your scripts.

if [ -f "env_vars.sh" ]; then
    source env_vars.sh
else
    echo "Environment configuration file not found."
fi
Conditional sourcing example to check env_vars.sh existence before sourcing

This method avoids sourcing a file that might not exist and provides user feedback if it isn’t found.

Example 2: Using Command Substitution

You can use source with command substitution to source dynamically generated content.

Dynamic Example:

source <(echo "export TEMP_VAR='Generated'")
echo $TEMP_VAR  # Outputs: Generated
Using source with command substitution to dynamically set TEMP_VAR

It can be utilized for dynamic configuration loading or the creation of environment variables on the go.

8. Differences Between source and. (Dot Command)

Both source and . achieve the same result: they execute a file from the shell that is currently up and running. The divergence makes distinctions based on readability and preference. The full-term source is used when referring to it for clarity, while It is used when mentioned briefly.

Example:

source script.sh  # Same as: . script.sh
source and dot command comparison for loading script.sh in shell

Use what aligns with your style or team’s conventions.

9. Best Practices for using Source

Use Absolute Paths for Reliability

Referencing absolute paths helps maintain consistency and prevents errors.

source /home/script.sh

Document Your Scripts

Adding comments within your sourced scripts helps others (and your future self) understand what the script does and why.

# This script sets up project-specific environment variables
export DB_USER='admin'

Be Mindful of Variable Overwrites

When sourcing files, make sure variable names are unique to avoid accidentally overwriting existing variables in the session.

10. Conclusion

The source command is a powerful tool for managing shell sessions, loading environment variables, and importing reusable functions. Its ability to execute scripts in the current shell session makes it ideal for quick reconfiguration and loading project-specific settings. By mastering the source, you can make your shell scripting more versatile and your development process more adaptable. Practice these examples, apply them in your work, and incorporate best practices for a reliable and effective Linux workflow.

About the writer

Vinayak Baranwal Article Author

Vinayak Baranwal wrote this article. Use the provided link to connect with Vinayak on LinkedIn for more insightful content or collaboration opportunities.

Leave a Reply

Your email address will not be published. Required fields are marked *

Lifetime Solutions:

VPS SSD

Lifetime Hosting

Lifetime Dedicated Servers