May 092013
 

It’s a common task when writing shell scripts to need to source a set of environment variables from an external configuration file. The advantage of this is that the dynamic variables can be abstracted from the script itself, which can then be more securely version controlled. In shell scripts, it’s a simple matter of assigning values to variables in a literal shell fashion, and then sourcing the config file from within the executable script with the dot “.” operator. Perl scripts will not accept this syntax, but it can often be useful to re-use shell config files. Here’s a simple and intuitive method to do so.

Short Answer

Iterate over each line in the shell config file and parse it like this:

      $$1 = $2 if /^([^=]+)=(.+)$/;

Long Example

In this example there is a file called “auth.cfg” which contains a username and password, assigned to the variables USER and PASSWORD respectively:

auth.cfg:
USER="backup"
PASSWD="password123"

The code displayed in the “short answer” above can be used an readably expanded to this:

   #!/usr/bin/perl

   my $cfgFile = "auth.cfg";
   open(CFG,"<$cfgFile") || die "Cannot open config file $cfgFile\n";
   while() {
      if (/^([^=]+)=(.+)$/) {
         $$1 = $2;     # Take the variable value as the literal name of a variable
      }
   }
   print "USER = $USER\n";
   print "PASSWD = $PASSWD\n";

The only catch is that the config file must accurately specify the name of the variable that the script expects (in “$$1”), otherwise the variable will be unassigned and the script’s behaviour could be unpredictable. Some form of error checking is therefore advised, but this will be left as an exercise to the reader.


Matt Parsons is a freelance Linux specialist who has designed, built and supported Unix and Linux systems in the finance, telecommunications and media industries.

He lives and works in London.

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>