Reusing Code with Includes and Sourcing

Problem

There are a set of shell variable assignments that you would like to have common across a set of scripts that you are writing. You tried putting this configuration information in its own script. But when you run that script from within another script, the values don’t stick; e.g., your configuration is running in another shell, and when that shell exits, so do your values. Is there some way to run that configuration script within the current shell?

Solution

Use the bash shell’s source command or POSIX single period (.) to read in the contents of that configuration file. The lines of that file will be processed as if encountered in the current script.

Here’s an example of some configuration data:

$ cat myprefs.cfg
SCRATCH_DIR=/var/tmp
IMG_FMT=png
SND_FMT=ogg
$

It is just a simple script consisting of three assignments. Here’s another script, one that will use these values:

#
# use the user prefs
# source $HOME/myprefs.cfg
cd ${SCRATCH_DIR:-/tmp}
echo You prefer $IMG_FMT image files
echo You prefer $SND_FMT sound files

and so forth.

Discussion

The script that is going to use the configuration file uses the source command to read in the file. It can also use a dot (.) in place of the word source. A dot is easy and quick to type, but hard to notice in a script or screen shot:

. $HOME/myprefs.cfg

You wouldn’t be the first person to look right past the dot and think that the script was just being executed.

bash also has a third syntax, one that comes ...

Get bash Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.