2014-04-04 81 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

相關問題