Chris F.A. Johnson
Unix shell programming notes

14 February 2002

Reading configuration files

Start-up files that control the behaviour of a program, or tell it where to look for its data, allow users to customize a program, and are easily implemented in shell scripts.

Whether you call them configuration files, initialization files, rc files, or something else, start-up files can be used to do anything from setting display colors to changing the behaviour of a program. They can tell the program where to find data it needs, where to put its temporary files, whether or not to ask the user for confirmation before taking an irreversible step, or a myriad of other things.

At their simplest, they are files with name and value pairs in the format name=value, for example:

A typical configuration file could look like this:

## NAME: .myprogrc
default_dir=/path/to/data
temp_dir=/path/to/tmp
verbose=3
clean_up_tempdir=no

In most programming languages, configuration files are read in and parsed line by line. The equivalent shell code goes something like this:

while IFS== read var val
do
  case $var in
    \#*) ;;  ## ignore commented lines
    *=*)  eval "$var=\$val" ;;
  esac
done < "$configfile"

In the shell, however, the values can be read in with a single command. All that’s necessary is to source the file:

. .myprogrc

Or, with bash, the word source may be used instead of the dot:

source .myprogrc

For this to work, the file must be a valid shell script. It means that values containing whitespace or other characters special to the shell must be quoted:

name="John Q. Public"

A program may have more than one configuration file; in that case, I use a command-line option to select between them. But that’s a subject for a future article.

Modified 17 Nov 2011