Site icon DesignLinux

Bash Source Command

Source Command

The source is a shell built-in command which is used to read and execute the content of a file, passed as an argument in the current shell script. It is useful to load functions, variables, and configuration files into shell scripts.

Source Command Syntax

The following is the basic syntax for the Source Command:

source FILENAME [ARGUMENTS]

Here,

Source Command Examples

Now we will shows few examples of how to use the source command:

Sourcing Functions

If you have shell scripts using the same functions, you can extract them in a separate file and then source that file in your scrips.

For an example, we will create a file with a bash function that will check whether the user running the script is the root, and if not, it shows a message and exits the script.

check_root () {
  if [[ $EUID -ne 0 ]]; then
    echo "You must run this script as root" 
    exit 1
  fi
}

Now in each script that needs to be run only by the root user, simply source the functions.sh file and call the function:

#!/usr/bin/env bash

source functions.sh
check_root

echo "It's root"

As a result, if you run the script above as a non-root user, it will print “You must run this script as root” and exit.

By this way you can reuse this function whenever needed and it’s easy to edit at one file only.

Bash Configuration file

The source command is also used to read variables from a file. The variables must be set using the Bash syntax, VARIABLE=VALUE.

For example, create a test configuration file named config.sh:

VAR1="welcome"
VAR2="again"

In your bash script, use the source command to read the configuration file:

#!/usr/bin/env bash

source config.sh

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

It should show output as following:

VAR1 is welcome
VAR2 is again

Conclusion

In this article, you have learned how to use the source built-in command in your shell scripts.

If you have any questions or feedback, feel free to leave a comment.

Exit mobile version