2014-02-12 72 views
1

我想從shell中的resolv.conf中讀取名稱服務器,並將它們存儲到數組中。但我使用的shell版本不支持數組。我收到錯誤代碼如下:需要從resolv.conf中讀取名稱服務器

cat /etc/resolv.conf 
i=1; 
grep 'nameserver' /etc/resolv.conf | awk '{print $2}' | \ 
       while read line; do name_server[$i]=$line; i=$((i+1)); done 

for i in "${name_server[@]}" 
do 
    echo $i 
done 

我得到以下錯誤:

nameserver x.y.z.w 
nameserver x.y.z.t 

line 4:name_server[1]=x.y.z.w: not found 
line 4:name_server[2]=x.y.z.t: not found 
line 6:syntax error: bad substitution 
+0

所以你的問題是什麼?如果您的shell不能這樣做,請使用另一個。我們不能神奇地迫使它工作。 –

+0

哦,這可能是一個好主意,可以使用_which_ shell你正在使用... – arkascha

+1

你可以使用'perl'或'python'作爲「shell」。 http://stackoverflow.com/questions/209470/can-i-using-python-as-a-bash-replacement – PeterMmm

回答

1

你可以試試下面

declare -a array=(`cat /etc/resolv.conf |grep nameserver|awk -F" " '{print $2}'`) 
echo ${array[0]} 
echo ${array[1]} 
1

這裏的蟒蛇解決方案

#!/usr/bin/python 

with open("/etc/resolv.conf","r") as readFile: 
    print [line.split(" ")[1].strip() for line in readFile.readlines() if line.startswith("nameserver")]