What is importing/Sourcing?

Importing files in Bash is a way to take a bash file, and implant (import) it in another script temporarily during runtime. This can be handy if you have a file that just has a couple functions in it, and you want to use those functions (sound a lot like programming?)

How To Source/Import Files

There are two ways to import files in bash, and both do the exact same thing, they just have different syntax. You can use the source command to import a file.

source functions.sh

…or you can also use a period.

. functions.sh

Sourcing is done when bash first starts when you open a terminal or ssh into a server using the bash shell. Bash first starts, and then it sources your .bashrc file or your .bash_profile file (depending on how you login), which reads in variables that pertain to that session of bash.

Example of Source

First

In this script you can see that it echos at both the beginning and at the end of the script. It also echos the variable $VARIABLE, which doesn’t actually exist in the script itself. The second command in this script is what we are most concerned with. It tells the script to read in, or source the file secondary.sh

If we run this script without creating secondary.sh, here’s what it does.

Second

As you can see it produces an error when it attempts to source the file because it does not exist, but it continues and finishes. Now we’ll create the file secondary.sh.

Third

As you can see this script only has one line, and sets the variable to a string. Now when the script main.sh is run it will execute successfully.

Fourth

From the output you can see that the script read in the variable from the other file, and was able to place it directly in main.sh. These two scripts are effectively equivalent to this when it comes to runtime execution:

Fifth

This is the power of sourcing files, it provides a simple way to read in a file containing a lot of commonly used functions, or an easy way of reading in a configuration file for a script.

Now that we have both scripts written, we are 99% done. Because sourcing a file will fail if the sourced file doesn’t exist, it is best to first test to see if the file exists. In this script I have modified the source line to first test for the files existence, and to set a variable if it DOESN’T exist.

[[ -f secondary.sh ]] && . secondary.sh || VARIABLE="No file found"

Sixth

All Done

This tutorial was a quick introduction to sourcing files, and though I only skimmed the surface of bash sourcing, it will definitely be enough to give you a good understanding and a good start on making your bash scripting much easier.