写shell脚本的时候,常常须要逐行读取文件内容,而咱们经常采用while read line重定向到文件,可是执行过程则会遇到问题:
cat list
172.16.50.175 t-1
172.16.50.176 t-2
172.16.50.177 t-3
172.16.50.178 t-4
172.16.50.179 t-5
cat get_hostname.sh
css
#!/bin/shshell
cat list | while read linessh
ip=`awk '{print $1}' tmp`ide
dospa
ssh $ip "hostname"orm
doneip
下面来看执行结果:
test-1.XXX.com
啊哦,彷佛while循环只执行了一行就不在执行了,这个很糟糕
那么如何来改进这个脚本呢?
get
#!/bin/shit
exec 3< listclass
while read -u3 line
do
ip=`echo $line |awk '{print $1}'`
ssh $ip "hostname"
done
exec 3<&-
好,再来执行,查看结果:
test-1.XXX.com
test-2.XXX.comtest-3.XXX.comtest-4.XXX.comtest-5.XXX.com好,结果是咱们想要的。至于为何,本身仔细思考