Merging Bash sources
Simon Wistow
simon at thegestalt.org
Wed Nov 11 01:19:05 GMT 2009
On Wed, Nov 11, 2009 at 01:03:08AM +0000, me said:
> 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.
Something like this in fact:
% cat try.sh
#!/usr/local/bin/bash
function loadConfig {
for line in `cat $1`;
do
name=`echo "$line" | cut -d '=' -f 1`
if [[ -z `echo "$line" | grep '='` || -z "$name" ]];
then
continue;
fi
value=`eval echo \\$${name}`
if [[ -z ${value} ]];
then
eval ${line}
fi
done
}
config="try.conf"
echo "Config is: "
cat ${config}
echo ""
echo ""
foo="a"
loadConfig ${config}
echo "Variables are now:";
echo "foo=${foo}"
echo "bar=${bar}"
% ./try.sh
Config is:
foo="quirka"
# foo
bar="fleeg"
Variables are now:
foo=a
bar=fleeg
More information about the london.pm
mailing list