写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

  1. #!/bin/sh

  2. cat list | while read line

  3. ip=`awk '{print $1}' tmp`

  4. do

  5. ssh $ip "hostname"

  6. done

下面来看执行结果:
test-1.XXX.com
啊哦,似乎while循环只执行了一行就不在执行了,这个很糟糕
那么如何来改进这个脚本呢?


  1. #!/bin/sh


  2. exec 3< list

  3. while read -u3 line

  4. do

  5. ip=`echo $line |awk '{print $1}'`

  6. ssh $ip "hostname"

  7. done

  8. exec 3<&-

好,再来执行,查看结果:
test-1.XXX.com
test-2.XXX.com
test-3.XXX.com
test-4.XXX.com
test-5.XXX.com

好,结果是我们想要的。
至于为什么,自己仔细思考