Merging Bash sources
Ash Berlin
ash_cpan at firemirror.com
Wed Nov 11 01:23:52 GMT 2009
On 11 Nov 2009, at 01:03, Simon Wistow wrote:
> I have a small problem in that I'm trying to modify a bash script so
> that currently does this
>
> . config
> # then inspect command line args
> getArgs
>
> so that you can specify the config file on the command line. Which
> necessarily requires do
>
> config_file="config"
> # inspect command line args first
> getArgs
> . ${config_file}
>
> however that means that anything in the config file will override
> anything passed in on the command line. Which sort of defeats the
> point.
>
> Is there an easy way to say "source this config file but don't
> override
> any variable already set?" or some sort of standard recipe? Or amy I
> going to have to write something that reads the config file line by
> line, splits out any variable name left of a '=' checks to see if it's
> set and then evals the line? Cos that's potentially prone to failure.
Bash does have some fairly complex substitution possibilities[0] such
as:
${foo:-bar} # If $foo exists and is not null, return $foo. If it
doesn't exist or is null, return bar.
${foo:=bar} # as above, but set foo=bar as well as returning
But I don't think any thse are ideal for your purposes, and you
probably don't want to require who ever is writing the config file to
have to do anything but "foo=bar"
So either re-process the args after you've loaded the config file, or
use different internal variables for cmd line flags and merge
afterwards.
-ash
[0] http://linux.die.net/abs-guide/parameter-substitution.html
More information about the london.pm
mailing list