2014-04-04 78 views
1

根据我的场景,需要从配置文件收集值。但是需要从配置文件访问值而不指定键。如何从Shell脚本的配置文件中检索值

source command我已经做了由以下

Configuration.conf

出口名称=值

出口年龄=值

出口地址检索值=值

Script.sh

source Configuration.conf 

echo $Name 
echo $Age 
echo $Address 

通过上面的方法,我可以从配置文件访问的值。


我想在不使用配置文件的密钥的情况下访问这些值。

在我上面的场景中,键将以任何形式改变(但值将会和我的逻辑类似)。在脚本中,我必须在不知道密钥名称的情况下读取值。像下面这样。

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

任何帮助,非常感谢。

+0

你给,'的例子,而[$ 1]'会做同样的,无论参数是什么。目前尚不清楚你想要达到的目标。 – devnull

+0

@devnull:真的很抱歉以混乱的方式提出问题。现在我改变了它。希望它能帮助你。 – ArunRaj

回答

2

假设配置文件仅包含与每个声明占据一行VAR =值声明。

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 
2

我会使用sedcut解析配置文件。像这样:

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 

输出继电器:

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

用grep从conf文件中提取密钥。使用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 
+0

它工作正常。对此感激不尽。怀疑你的代码。请分享我的知识。 **没有使用源代码命令你的代码工作正常。怎么可能?** **以何种方式将密钥和值存储在内存中** – ArunRaj

+1

您必须先在当前shell中找到conf文件。启动一个新的外壳,然后再试一次 –

+0

谢谢杰克。明白了。 – ArunRaj

相关问题