Linux 101: What does “sourcing a file” mean in Linux?

Linux 101: What does “sourcing a file” mean in Linux?

Jack Wallen explains the Linux source command by way of an example.

linux-1.jpg

Image: Larich/Shutterstock

More about open source

Sourcing a file in Linux is a very important concept, but it might not be one you’ll use early on in your Linux career. Even so, I’m going to try to explain this challenging concept in a way you can understand it. 

Sourcing a file makes it possible for an executable to “source” information from a script as though the script had printed its output to the terminal. It’s not an easy concept to grasp, so I’m going to show you by way of an example. 

SEE: 5 Linux server distributions you should be using (TechRepublic Premium)

Let’s start with a shell script, named sudocheck.sh that contains a few simple lines of code that warn any script that uses its output must be run with sudo privileges. That script might look something like this:

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

Next, we’ll create an executable file, named checksudo.sh, that will use the output of sudocheck.sh and print out if the execution has been done with sudo privileges. That file might look something like this:

#!/usr/bin/env bash
source sudocheck.sh
check_root
echo "I have sudo privileges"

The checksudo.sh file will source the sudocheck.sh file and use the resulting output. 

Before we actually execute the file, issue the command chmod u+x checksudio.sh. Now, issue the command ./checksudo.sh and you should see printed “You must run this script with sudo privileges.” 

However, if you run the command sudo ./checksudo.sh you’ll see I have sudo privileges printed out. So the second script uses the output of the first as a source for input. 

SEE: Rust: What developers need to know about this programming language (free PDF) (TechRepublic)

By using this device, you can create more streamlined scripts that source multiple files. You could also use the source command in your scripts to read configuration files, to save space and time. 

And that’s the source command in a nutshell … or a bash shell, however, you want to look at it.

Also see

Source of Article