pradsh
1
How do i use a config.txt to recursively pass a set of variables to a shell script
eg my config.txt looks like this :
[set_1]
path=c://dataset/set1
v1= a.bin
v2= b.bin
[set_2]
path=c://dataset/set2
v1= xy.bin
v2= abc.bin
[set_3]
..................
and so on .
and my testscript :
#!/bin/bash
.$1
echo $path $v1 $v2
Right now I am able to parse first set of variables . How do i move on to the subsequent set_2 , set_3 ...........
Thanks in advance
pradsh
You can do something like that :
# Function: get_config_list config_file
# Purpose : Print the list of configs from config file
get_config_list()
{
typeset config_file=$1
awk -F '[][]' '
NF==3 && $0 ~ /^\[.*\]/ { print $2 }
' ${config_file}
}
# Function : set_config_vars config_file config [var_prefix]
# Purpose : Set variables (optionaly prefixed by var_prefix) from config in config file
set_config_vars()
{
typeset config_file=$1
typeset config=$2
typeset var_prefix=$3
typeset config_vars
config_vars=$(
awk -F= -v Config="${config}" -v Prefix="${var_prefix}" '
BEGIN {
Config = toupper(Config);
patternConfig = "\\[" Config "]";
}
toupper($0) ~ patternConfig,(/\[/ && toupper($0) !~ patternConfig) {
if (/\[/ || NF <2) next;
sub(/^[[:space:]]*/, "");
sub(/[[:space:]]*=[[:space:]]/, "=");
print Prefix $0;
} ' ${config_file} )
eval "${config_vars}"
}
#
# Set variables for all config from config file
#
file=config.txt
for cfg in $(get_config_list ${file})
do
echo "--- Configuration [${cfg}] ---"
unset $(set | awk -F= '/^cfg_/ { print $1 }') cfg_
set_config_vars ${file} ${cfg} cfg_
set | grep ^cfg_
done
Input file (config.txt)
[set_1]
path=c://dataset/set1
v1= a.bin
v2= b.bin
[set_2]
path=c://dataset/set2
v1= xy.bin
v2= abc.bin
[set_3]
v1 = value1
Output:
--- Configuration [set_1] ---
cfg_path=c://dataset/set1
cfg_v1=a.bin
cfg_v2=b.bin
--- Configuration [set_2] ---
cfg_path=c://dataset/set2
cfg_v1=xy.bin
cfg_v2=abc.bin
--- Configuration [set_3] ---
cfg_v1=value1
Since you aren't worried about accessing the First Set of Variables again, you can just source the second set... Using your example:
[set_1]
path=c://dataset/set1
v1= a.bin
v2= b.bin
[set_2]
path=c://dataset/set2
v1= xy.bin
v2= abc.bin
[set_3]
..................
and so on .
and my testscript :
#!/bin/bash
.$1 #Here you are sourcing set 1 - I assume
echo $path $v1 $v2 #here you are showing the variables
. $2 #Here you are sourcing set 2
echo $path $v1 $v2 #here you are showing the new variables
# Just make sure to call the script with the variable files as the first and second argument.