Exploiting the Bourne shell to parse configuration files
Suppose that you have what I will call a 'directive style' configuration file, where it looks something like (say):
fileserver fs1 exportto hostsa:hostsb filesys /h/10 fs1/d100 filesys /h/11 fs1/d110
Further, suppose that you want to do things with this configuration file in a Bourne shell script, which requires parsing it to extract all of the information that you're interested in.
Normally this would be a pain, but it's recently struck me that you can
exploit Bourne shell functions to do the parsing for you. Simply define
a function for each directive that does something appropriate with its
parameters, and then source the actual configuration file from your
scripts (with the '
.' operator). Bang, you're done, and you even get
comments and line continuations for free.
(If you want to make this the official way that the configuration file is parsed, you can give people a fair amount of power with just things like shell variables to capture common pieces. You probably don't want to go all the way to encouraging them to use conditions and loops and so on, so that you can at least pretend that the configuration file can be parsed by something other than your Bourne shell scripts.)
Of course, half of making this useful here is figuring out how to represent and store the parsed data, since the Bourne shell is not exactly known for its data structures. But given that your main shell script code needs to use the information, you can always work backwards from how that code wants it to figure out a representation. And if you don't need all of the information (and you probably don't), you can just discard most of it, which simplifies storing the rest of it.
Disclaimer: this probably qualifies as an evil hack.