There's no need for external tools such as sed
at all, or for the security risks involved in using source
(being, as it is, a moral equivalent to eval
). The following is a best-practices approach for bash 4.0 or newer:
shopt -s extglob # enable +()
declare -A config=( )
while IFS='=' read -r k v; do
[[ $v ]] || continue # skip lines that aren't assignments
[[ $k = '#'* ]] && continue # skip comments
k=${k%+([[:space:]])} # trim trailing whitespace from keys
v=${v#+([[:space:]])} # trim leading whitespace from values
config[$k]=$v
done <Example.config
This lets you refer to configuration-file data as ${config[foo]}
, keeping it in a separate namespace from variables such as $foo
. This is actually a better practice for security: It ensures that variables such as LD_PRELOAD
or PATH
that can impact system security can't be modified behind your back.
It also makes your configuration format more flexible, letting you use configuration option names that aren't valid shell variables (containing dashes, spaces, etc). For instance, you could allow:
# in your Example.config
server name = hello
...and...
# in your code
echo "Using server name: ${config['server name']}"