Ubuntu – Best way to read a config file in bash

bash

What is the best way to read a config file in bash?
For example, you have a script and aren't willing to fill in all the config manually each time you call the script.

Edit 1:
I think I didn't make it clear, so: what I want is… I have a configfile which is like

variable_name value  
variable_name value ...  

and I want to read that. I know I could just grep it for the arguments I'm looking for or so… but maybe there's a more intelligent way 🙂

Best Answer

As mbiber said, source another file. For example, your config file (say some.config) would be:

var1=val1
var2=val2

And your script could look like:

#! /bin/bash

# Optionally, set default values
# var1="default value for var1"
# var1="default value for var2"

. /path/to/some.config

echo "$var1" "$var2"

The many files in /etc/default usually serve as configuration files for other shell scripts in a similar way. A very common example from posts here is /etc/default/grub. This file is used to set configuration options for GRUB, since grub-mkconfig is a shell script that sources it:

sysconfdir="/etc"
#…
if test -f ${sysconfdir}/default/grub ; then
  . ${sysconfdir}/default/grub
fi

If you really must process configuration of the form:

var1 some value 1
var2 some value 2

Then you could do something like:

while read var value
do
    export "$var"="$value"
done < /path/to/some.config

(You could also do something like eval "$var=$value", but that's riskier than sourcing a script. You could inadvertently break that more easily than a sourced file.)