ArunRaj
ArunRaj

Reputation: 1790

How to retrieve values from configuration file for Shell Scripts ( Without the knowledge of Keys )

As per my scenario, Need to collect values from configuration files. But need to access values from the configuration files without specifying the keys.

By the source command I have done it to retrieve values by the following

Configuration.conf

export Name=value

export Age=value

export Address=value

Script.sh

source Configuration.conf

echo $Name
echo $Age
echo $Address

By the above way I could access the values from the configuration files.


I would like access the values without using the key of the configuration files.

In my above scenario, Key will be changing in any form (But values are going to be similar as well my logic). At the script I have to read the values without knowing the Key name. something like the following.

source Configuration.conf
while [ $1 ] // Here 1 is representing the first Key of the configuration file. 
do
//My Logics
done

Any help is much appreciated.

Upvotes: 1

Views: 3939

Answers (3)

glenn jackman
glenn jackman

Reputation: 247012

Extract the keys from the conf file with grep. Get the values using variable indirection.

keys=( $(grep -oP '\w+(?==)' conf.conf) )
for (( i=0; i < ${#keys[@]}; i++ )); do
    printf "%d\t%s\n" $i "${keys[i]}"
done
echo
source conf.conf
for var in "${keys[@]}"; do
    printf "%s\t=> %s\n" "$var" "${!var}"
done
0   Name
1   Age
2   Address

Name    => name_value
Age     => age_value
Address => addr_value

Upvotes: 2

dave sines
dave sines

Reputation: 36

Assuming the configuration file only contains var=value declarations with each declaration occupying a single line.

configfile=./Configuration.conf

. "$configfile"

declare -A configlist

while IFS='=' read -r key val ; do

  # skip empty / commented lines and obviously invalid input
  [[ $key =~ ^[[:space:]]*[_[:alpha:]] ]] || continue

  # Stripping up to the last space in $key removes "export".
  # Using eval to approximate the shell's handling of lines like this:
  #    var="some thing with spaces" # and a trailing comment.
  eval "configlist[${key##* }]=$val"

done < "$configfile"

# The keys are "${!configlist[@]}", the values are "${configlist[@]}"
#
#for key in "${!configlist[@]}" ; do
#  printf '"%s" = "%s"\n' "$key" "${configlist[$key]}"
#done

for value in "${configlist[@]}" ; do
  : your logic goes here
done

Upvotes: 2

hek2mgl
hek2mgl

Reputation: 158110

I would parse the config file using sed and cut. Like this:

sed -n 's/export//p' conf.sh | while read expression ; do 
    key=$(cut -d= -f1 <<< "$expression")
    value=$(cut -d= -f2 <<< "$expression")

    # your logic comes here ...
    echo "$key -> $value"
done

Ouput:

Name -> value
Age -> value
Address -> value

Upvotes: 2

Related Questions