Understand the source Command in Linux: 4 Practical Examples

Try this guide with our instant dedicated server for as low as 40 Euros

source command

If you are a Linux user, you may have already come across various situations where you used the source command. 

The source command is a powerful built-in shell command that reads and executes file content in the current shell. Unlike other commands that execute a script in a new shell, the source command executes a script in the current shell.

During the execution, any variables or functions that the script defines or modifies will be available in the current shell. This allows any changes, like setting variables or defining functions, to become available for use immediately in the current terminal window.

In this tutorial, we will discuss what is the source command, its syntax, and some use cases. 

Let’s start with an overview of the source command.

Table Of Contents

  1. What is the source Command?
    1. The Basic Syntax
    2. Features of source Command
  2. 4 Use Cases of source Commands
    1. Example #1: Define a Function
    2. Example #2: Pass Arguments
    3. Example #3: Set Environment Variables in a Configuration File or a Shell Script
    4. Example #4: Refresh the Current Shell Environment
  3. Conclusion
  4. FAQs

What is the source Command?

The source command in Linux, also known as dot (.), is a versatile utility that executes shell scripts within the current shell environment. Unlike directly executing a script, which launches a new subshell, the source command incorporates the script’s contents directly into the current shell session. 

The Basic Syntax

The source command executes commands from a specified file within the shell environment. 

The basic syntax of source command is:

# source filename

OR

# . filename

Features of source Command

The source command is a popular choice for executing scripts in the current shell. Here are a few features that make it a good fit for script execution.

Seamless Integration

Changes made by the sourced script, such as setting environment variables or function activities, become immediately functional in the current shell session and persist until the exit of the shell. This allows for a more streamlined workflow.

Organization and Readability

By separating configurations or functions into dedicated script files, source promotes cleaner and more organized main scripts. This enhances the readability and maintainability of your scripts.

Executable Permissions Not Required

 A script sourced doesn’t necessarily need to have executable permissions for the source to work. This is often useful in situations where the configuration files or helper functions don’t require strict execution control. 

Note: These files might contain sensitive information. Therefore, we strongly recommend having executable permissions to provide an extra layer of security by restricting who can execute the script directly (with ./script.sh). 

Portability 

The source command is supported by most POSIX-compliant shells, including Bash, Zsh, and Ksh. This ensures that the scripts using source will work consistently across different Linux environments without modification.

Flexibility in Script Location

The source command can handle absolute paths (the full directory structure) or relative paths (locations relative to the current working directory) to locate the script the user wants to source. This provides flexibility in organizing scripts and configuring files.

At this point, you have enough background information to understand the use cases we will now discuss.

The Prerequisites

Before diving into the use cases of source command, ensure you have the following.

  • A system running a popular Linux distribution
  • A user account with root or sudo privileges
  • Access to the terminal/command line.

4 Use Cases of source Commands

The source command is a powerful tool for incorporating functionality from external files into the current shell session. You can use it in several application scenarios. We will discuss the following four common ones. 

Example #1: Define a Function

Consider the scenario where you have a text file functions.sh in the home directory. This file contains the following custom function:

# functions.sh

say_hello() {

echo "Hello, $1!"

} 

Use the source command to source the functions.sh script into your current shell session: 

# source functions.sh

Once you have sourced the script, you can invoke the say_hello function.

# say_hello "Alice"

The output of the script will be:

Hello, Alice!

cat functions

Example #2: Pass Arguments

The source command executes a script within the current shell session and passes arguments. This is different from running the bash script, which creates a new shell environment.

You can follow these steps to pass arguments to a script using source:

Step #1: Create the Script

Create a shell script (we will name it hello.sh) that accepts a name as an argument and prints a greeting:

# hello.sh

# !/bin/bash

echo "Hello, $1!"

Step #2: Pass Arguments Using source

We will now use the source command to pass an argument to the hello.sh script and execute it within the current shell session. The syntax of the command will be as follows: 

# source hello.sh “Alice”

source hello. sh alice

The command outputs: 

Hello, “Alice”!

Example #3: Set Environment Variables in a Configuration File or a Shell Script

You can also use the source command to set environment variables in a configuration file or shell script. The steps in this process are as follows: 

Step #1: Create a Configuration File

Create a configuration file or a bash script containing the following environment variable assignments. We will name this file config.sh:

# config.sh

export MY_VAR="123"

export SERVER_IP="192.168.1.100"

Step #2: Source the Configuration File

Next, use the source command to read and apply the settings from the config.sh file in your current shell session.

# source config.sh

Step #3: Access the Environment Variables 

Now that you have sourced the configuration file, you can use the environment variables MY_VAR and SERVER_IP in your current shell.

# echo “$MY_VAR”

# echo “$SERVER_IP”

echo server ip

Example #4: Refresh the Current Shell Environment

In our scenario, we have made changes to the shell environment and want to implement them without logging out and back in. The following steps discuss how to refresh the current shell environment without logging out. 

Step #1: Create the Refresh Script

Create a script refresh.sh to reload the shell profile.

# refresh.sh

#!/bin/bash

source ~/.bashrc

Step #2: Make the Script Executable

Next, ensure the script has execute permissions by running the following chmod command:

# chmod +x refresh.sh

Step #3: Source the Refresh Script

To refresh your current shell environment, using the refresh.sh script, run:

# source refresh.sh

source refresh

This will reload your .bashrc file, applying any changes made since the last login.

Conclusion

The source command is an essential tool within Linux and Unix-like systems that significantly enhances the flexibility and control of the shell environment. As we’ve seen through the practical examples, source enables users to dynamically load and execute scripts within the current shell process without spawning a new shell. 

From passing arguments and reading configuration files to sourcing functions and refreshing the current shell environment, the source command proves itself as one of the fundamental tools for any system administrator or power user. It allows for a more interactive and responsive shell experience and ensures changes are applied instantaneously across the session, which is particularly valuable in complex script execution and system setup scenarios.

FAQs

Q. What is the source command in Linux?

The source command, a built-in Linux shell command, executes commands from a specified file within the current shell process. This command is handy for updating the script or shell environment without opening a new terminal session.

Q. How does the source command differ from running a script normally?

Running a script normally (e.g., ./script.sh) executes in a new subshell. Any changes to environment variables, like the PATH variable, are not reflected in the original shell. In contrast, the source command executes the script within the current shell process, allowing any environmental changes to take immediate effect.

Q. Can the source command affect the PATH environment variable?

Yes, sourcing a script that modifies the PATH environment variable will add the specified directory to your current PATH, persisting until the shell session ends.

For example: 

# update_path.sh

export PATH="$PATH:/opt/newpath" 

Sourcing this script with source update_path.sh will add /opt/newpath to the current PATH variable, affecting command searches in the ongoing session.

Q. How do I use the source command at the command prompt?

At the command prompt, you can use the source followed by the file name to execute the script within the current shell. For instance:

# source ./my_script.sh

This command sources my_script.sh, immediately applying its effects (like environment variable changes or function definitions) to the current shell.

Q. What is a common mistake to avoid when using the source command?

A common mistake is forgetting that the source command does not automatically locate scripts not in the current directory or listed in the PATH variable. Always specify the full path if the script is not in the current directory or add its directory to the PATH environment variable. 

Q. Why would I use the source command instead of executing a script directly?

Using the source command is particularly beneficial when you want changes made by a script (like setting environment variables or defining functions) to persist in the current shell. This is essential in situations where you need to maintain the state of the current script environment, such as setting up a development environment or modifying the shell configuration dynamically.

Q. How can I ensure that a script sourced at the command prompt does not disrupt my current shell?

Always review a script before sourcing it to understand the changes it makes to your environment. If they contain significant modifications, consider testing them in a separate shell session or virtual environment to ensure they do not disrupt your primary shell setup.

Try this guide with our instant dedicated server for as low as 40 Euros