How to use Linux source command?

The source in Linux is a shell built-in command used to read and execute the commands from a file in the current shell. It is useful to load functions, variables, and configuration files in the shell script.

If the filename passed to the source command is not the full path of the file then it will search the filename in the directories specified in the $PATH variable. If the file is not found in the directories mentioned in $PATH then it will search filename in the current working directory. If any arguments are supplied they become the positional parameters when the file is executed.

In this article, you will see the usage of the Linux source command with some examples.

The syntax of Linux source command

The basic syntax of how to use source command in Linux is given below.

source filename [argument]

Where filename is the name of the file to source and argument are the values supplied from the command line. If the source command doesn’t found the filename it will return exit code 1 otherwise it will be 0.

Usage of Linux source command

The following example shows the usage of the Linux source command.

Example 1: Execute a list of commands using the source command

Suppose we have a file named testfile.txt this contains a list of commands. You can see the content of this file in the given image.

When you use this command each command given in the file will be executed one by one and the output will be printed on the terminal.

source testfile.txt

You can see the output of this command in the image below.

Example 2: Sourcing functions and configuration files

Create a shell script called mylib.sh as follows:

#!/bin/bash
JAIL_ROOT=/www/httpd
is_root(){
   [ $(id -u) -eq 0 ] && return $TRUE || return $FALSE
}

Now save this file and exit from the editor. You can call the function is_root() given in mylib.sh in any script, you can see the syntax in the given script test.sh.

#!/bin/bash
# Load the  mylib.sh using source comamnd
source mylib.sh

echo "JAIL_ROOT is set to $JAIL_ROOT"

# Invoke the is_root() and show message to user
is_root && echo "You are logged in as root." || echo "You are not logged in as root."

Provide executable permission to test.sh.

chmod +x test.sh

You can run this script using the given command.

./test.sh

This will produce the output something like this:

JAIL_ROOT is set to /www/httpd
You are not logged in as root.

Conclusion

I hope you understand how to use the source command in Linux. Now if you have any query then write us in the comments below.

Leave a Comment