We help IT Professionals succeed at work.

Easy way to read/set config file values?

jbbarnes asked
Can someone recommend an easy way to get a value out of a "standard" config file without a lot of parsing?

Most config files I deal with are some variation of this format:

# This is a comment line
key1 = value1
key2 = value2

Or often without the equals sign.

; This is a comment line
key1   value1
key2   value2

I know I can open the file and parse out anything I need, but it's a lot of extra code. Just wondering if there is a unix utility or BASH command to do it. Something like:

getval -f /etc/myfile.conf -k key1

that will handle most types of config files and can find values and ignore comments.

If not, how about a couple of unix commands piped to each other? If it's anything that can be typed at the prompt, then I could execute it within perl and php scripts and capture the return value.

Naturally, it would also be great to have a one-liner that will update a value in a config file.


Watch Question

Top Expert 2007

If they are in the form


then you can simple do

. /etc/myfile.conf

Note that is a dot and a space followed by /etc/myfile.conf


I don't really understand that.

It's not specifying which key in the file I'm trying to get a value for. I'm not trying to execute anything in that file, but read the values.
Top Expert 2007

Dot space will "source" the file.  It's sort of like an include in other languages.

Say myfile.conf has


then in your script you can do:

. /etc/myfile.conf

echo "var1=$var1"
echo "var2="$var2"

Perhaps I've misunderstood your requirements, but I think that's what you were after.
Top Expert 2005
use the following function

function getConfigValue {
 local key=$1
 local file=$2
 [ -n "$key" -a -f "$file" ] || return
 perl -ne "print \$1 if (/^${key}\s*=?\s*(\S+)/)" $file
value=$( getConfigValue keyName /path/to/cfg.file )

You really need one-liner?

value=$( perl -ne "print \$1 if (/^keyName\s*=?\s*(\S+)/)" /path/to/cfg.file )

Perhaps take a look at the Config::Simple module http://search.cpan.org/~sherzodr/Config-Simple-4.59/Simple.pm and some similar modules in the "See also" section.