Why source a file?

The first time you either see a . (dot) in a line of shell programming or someone tells you to source a file, you're first reaction is "huh?"  I did it, and I even heard it in a colleague's voice on a phone call last week. My colleague was by no means a junior IT person, but I could still hear the confusion. I decided to try and clarify for some folks so they don't struggle as much as we did.

Sourceis a shell builtin.  That means source is actually part of the shell program on your system. It's not a separate command that you can find on the system. That might be /bin/bashor/bin/shor /bin/cshshell or ...    If you type man source, you may get a reference, but you'll find out that the man page is actually the shell man page referencing shell builtin.  

NOTE: In older Unix/Linux shells source and "." (dot) used to be interchangeable.  If your shell is POSIX compliant, the . (dot) won't work. The best practice is to use the word source.

At it's simplest, source means to run a command in the current shell.  Remember that when you login, you are given a shell to work in.  If you run a command, it creates a child shell.  That means it inherits the default settings from your login shell, spawns a child shell (or sub-shell) to run the command and then exits.  If you question this, login to a Unix/Linux system and run a ps command.  You will see two lines, one line shows sh and one line shows ps.  That's because the ps command created a sub-shell to run in.

But maybe you need to do some debugging work or  web design work and need settings to make the work easier. How?  Do you want to type/srv/www/htdocs/or ${WWW}?  Would you prefer to type /srv/vhosts/site1/  or ${SITE1}?  I thought so, so let's find out how to make sourcework for us.

A file to be sourced is a shell script.  You create the file by beginning exactly the same way you any other shell script. Let's walk through a short example that you might use to do web design.

The first thing that goes in any shell script is the she-bang line.  This is the very first line in a script that specifies what shell or program that should run the script.  This usually looks like #!/bin/bash, or #!/bin/sh.  Any information that you want to add can be added in comment lines.  I encourage you to add anything that is part of why you are doing this in the first place.  Trust me, you won't remember it next year, when you need to edit the file.

Now enter any variable declarations you want to be able to use when you're doing web design.  Enter them as a single declaration per line for ease in reading.  An example would be WWW=/srv/www/htdocs. When you get all declarations entered, you need to export them so they'll be available from the command line.  That syntax is export WWW.  Proofread your file carefully and save it.

To see the difference that this will make, type the following:

env > env1

source ./webrc

env > env2