How to Check if Bash Script is Being Sourced

How to Check if Bash Script is Being Sourced

Bash Script is a powerful programming feature supported by every Linux system that allows Linux developers and system administrators to automate tasks and processes. Sometimes people run a standalone bash script whereas in other cases they source a script in another script, thereby sharing variables and functions. It is important to know if the bash script is called directly or sources from elsewhere to be able to control the program flow of your script.

How to Check if Bash Script is Being Sourced

Let us understand the two different ways to execute a shell script.

  1. Direct Execution – In this case, when you run a shell script it creates a separate process and executes the shell script within it, with its own variables. They are available only within the process and not available elsewhere. They will all be destroyed when the execution completes.
  2. Sourcing – In this case, you source another shell script into your script and so it runs in the same shell as your script. All variables and functions defined in the sourced script is available to you and continues even after that script completes execution.

You can find out is a script is directly executed or sourced using $0 and BASH_SOURCE variables. IN Bash, $0 contains the name of script whereas BASH_SCRIPT is an array variable that contains source history.

${BASH_SOURCE[0]} contains source of the current subroutine call, ${BASH_SOURCE[1]} contains the source of the caller of current subroutine, and so on. If a script is sourced, ${BASH_SOURCE[0]} will contain the name of the script itself.

Here is a code snippet to check if the script is sourced or not.

if [[ "${BASH_SOURCE[0]}" == "${0}" ]]
then
    echo "Script is being run directly."
else
    echo "Script is being sourced."
fi

Why is it important to know if a script is being run directly or sourced? Here is an example of a script that contains provisions to be run directly as well as via sourcing. By detecting invocation method, you can control its program flow.

# function definitions...
function1() { ... }
function2() { ... }

# if script is run directly, execute a command
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    function1
    function2
fi

In the above case, function1 and function2 are called only if it is run directly. If it is sourced, then only their definitions are processed.

In this article, we have learnt how to check if bash script is sourced or not.

Also read:

Where is PostgreSQL Configuration File Located
How to Speed Up File Transfer in USB Flash Drive in Windows
How to Fix ‘Every Derived Table Must Contain Alias’ MySQL Error
How to Fix MySQL Error Code 1903: Can’t Specify Target Table
How to Setup Email Notifications in Django

Leave a Reply

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