Jack Wallen explains the Linux source command by way of an example.
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:
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:
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: How-to guide for Linux administrators (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.
You don’t want to miss our tips, tutorials, and commentary on the Linux OS and open source applications. Delivered Tuesdays
Jack Wallen is an award-winning writer for TechRepublic, The New Stack, and Linux New Media. He’s covered a variety of topics for over twenty years and is an avid promoter of open source. For more news about Jack Wallen, visit his website jackwallen….
Hiring kit: Computer Vision Engineer
Google Docs tips for advanced users
Checklist: Mergers & Acquisitions
Hiring kit: Data Scientist