2012-09-05 93 views
7

我有以下內容的配置文件:bash腳本讀取文件中的變量到本地變量

msgs.config:

tmsg:This is Title Message! 
t1msg:This is T1Message.  
t2msg:This is T2Message.  
pmsg:This is personal Message! 

我寫一個bash腳本,讀取msgs.config文件變量並將它們存儲到局部變量中。我將在整個劇本中使用這些內容。由於許可,我不想使用.方法(來源)。

tmsg 
t1msg 
t2msg 
pmsg 

任何幫助將不勝感激。

+1

*由於許可,我不想使用。方法(來源)*不知道這將如何幫助,但你只需要讀取權限使用'源',如果你不能讀取它... – cdarke

回答

8

您可以使用:

oldIFS="$IFS" 
IFS=":" 
while read name value 
do 
    # Check value for sanity? Name too? 
    eval $name="$value" 
done < $config_file 
IFS="$oldIFS" 

或者,您可以使用關聯數組:

declare -A keys 
oldIFS="$IFS" 
IFS=":" 
while read name value 
do 
    keys[$name]="$value" 
done < $config_file 
IFS="$oldIFS" 

現在你可以參考${keys[tmsg]}等來訪問變量。或者,如果變量列表是固定的,你可以將值映射到變量:

tmsg="${keys[tmsg]}" 
+1

沒有必要保存'oldIFS';你可以用'while IFS =:read name value'來限制'IFS'到'read'命令的改變。另外,使用'declare'$ name = $ value'而不是'eval'。 – chepner

+0

感謝您的所有幫助。您建議: oldIFS =「$ IFS」 IFS =「:」 while IFS =:read name值 做 \t申報 「$名稱= $值」 完成<$ CONFIG_FILE – thegreat078

+0

@ thegreat078:這項建議是爲了避免'完全,只是oldIFS'使用:'而IFS = ':' 讀名在環value'(所以你不需要在循環之後重置IFS)假設它有效,這是合理的,如果'declare $ name =「$ value」'符號有效(我沒有理由認爲它沒有,但是被卡在一臺機器上,Bash 3.2沒有關聯數組),那麼肯定比「eval」(它幾乎總是在玩火,但是有些必要的時間; OTOH,Bash做了很多事情,使它不再像以前那樣必要,這是一件好事™!) –

1

讀取文件,並存儲值 -

i=0 
config_file="/path/to/msgs.config" 

while read line 
do 
    if [ ! -z "$line" ] #check if the line is not blank 
    then 
    key[i]=`echo $line|cut -d':' -f1` #will extract tmsg from 1st line and so on 
    val[i]=`echo $line|cut -d':' -f2` #will extract "This is Title Message!" from line 1 and so on 
    ((i++)) 
    fi 
done < $config_file 

訪問數組變量${key[0]}${key[1]},......和${val[0]}${val[1]} ...

1

萬一你改變主意source

source <(sed 's/:\(.*\)/="\1"/' msgs.config) 

這並不工作,如果你的任何值有雙引號。