Best way to read a config file in bash

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.)


Use source or . to load in a file.

source /path/to/file

or

. /path/to/file

It's also recommended to check if the file exists before loading it because you don't want to continue running your script if a configuration file is not present.


Obviously, I am not the bash specialist here, but the concept should not be different in whatever language you use:

An example

In the example below, you can use a (very) basic script to either set a string, or print a string, as set in your config file:

#!/bin/bash

# argument to set a new string or print the set string
arg=$1
# possible string as second argument
string=$2
# path to your config file
configfile="$HOME/stringfile"

# if the argument is: "set", write the string (second argument) to a file
if [ "$arg" == "set" ]
then
echo "$string" > $configfile 
# if the argunment is "print": print out the set string, as defined in your file
elif [ "$arg" == "print" ]
then 
echo "$( cat $configfile )"
fi

Then

  • To set a string into your config file:

    $ '/home/jacob/Bureaublad/test.sh' set "Een aap op een fiets, hoe vind je zoiets?"
    
  • Subsequently, to print out the string, as defined in your "configfile":

    $ '/home/jacob/Bureaublad/test.sh' print
    Een aap op een fiets, hoe vind je zoiets?
    

Of course, in a real applied script, you need to add a lot of stuff to make sure the arguments are correct, decide what to do when input is incorrect, settings file does not exist etc, but:

This is the basic idea

Tags:

Bash