Addison
Addison

Reputation: 8407

Using awk to parse a config file

I'm trying to make an awk command which stores an entire config file as variables.

The config file is in the following form (keys never have spaces, but values may):

key=value
key2=value two

And my awk command is:

$(awk -F= '{printf "declare %s=\"%s\"\n", $1, $2}' $file)

Running this without the outer subshell $(...) results in the exact commands that I want being printed, so my question is less about awk, and more about how I can run the output of awk as commands.

The command evaluates to:

declare 'key="value"'

which is somewhat of a problem, since then the double quotes are stored with the value. Even worse is when a space is introduced, which results in:

declare 'key2="value' two"

Of course, I cannot remove the quotes or the multi-word values cause problems.

I've tried most every solution I could find, such as set -f, eval, and system().

Upvotes: 2

Views: 2079

Answers (1)

Inian
Inian

Reputation: 85855

You don't need to use Awk for this but the do this with built-ins available. Read the config file properly using input redirection

#!/bin/bash

while IFS== read -r k v; do
    declare "$k"="$v"
done < config_file

and source the file as

$ source script.sh
$ echo "$key"
value
$ echo "$key2"
value two

If source is not available explicitly, POSIX-ly way of doing it would be to do just

. ./script.sh

Upvotes: 3

Related Questions