2014-02-12 71 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")]