ssh导致while read line出错

     -n      Redirects stdin from /dev/null (actually, prevents reading from stdin).  This must be used when ssh is run in the
             background.  A common trick is to use this to run X11 programs on a remote machine.  For example, ssh -n
             shadows.cs.hut.fi emacs & will start an emacs on shadows.cs.hut.fi, and the X11 connection will be automatically
             forwarded over an encrypted channel.  The ssh program will be put in the background.  (This does not work if ssh
             needs to ask for a password or passphrase; see also the -f option.)
#/bin/bash
IPS="10.1.1.10 3001
10.1.1.10 3003
10.1.1.11 3001
10.1.1.11 3002
10.1.1.11 3004
10.1.1.11 3005
10.1.1.13 3002
10.1.1.13 3003
10.1.1.13 3004
10.1.1.14 3002"
echo "====while test ===="
i=0

echo $IPS | while read line
do
    echo $(($i+1))
    echo $line
done


echo "====for test ===="
n=0
for ip in $IPS ;
do
   n=$(($n+1))
   echo $ip
   echo $n
done

输出结果如下:

====while test ====
1
10.1.1.10 3001 10.1.1.10 3003 10.1.1.11 3001 10.1.1.11 3002 10.1.1.11 3004 10.1.1.11 3005 10.1.1.13 3002 10.1.1.13 3003 10.1.1.13 3004 10.1.1.14 3002
====for test ====
10.1.1.10
1
3001
2
10.1.1.10
3
3003
4
10.1.1.11
5
3001
6
10.1.1.11
.... 
  • 由例子可见,while read line 是一次性将信息读入并赋值给line ,而for是每次读取一个以空格为分割符的字符串。

  • 【原因】
    while中使用重定向机制,IPS中的所有信息都被读入并重定向给了整个while 语句中的line 变量。所以当我们在while循环中再一次调用read语句,就会读取到下一条记录。问题就出在这里,$line中的最后一行已经读完,无法获取下一行记录,从而退出 while循环。

  • 【解决方法】
    1 使用ssh -n "command"
    2 ssh "cmd" < /dev/null 将ssh 的输入重定向输入。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,908评论 18 139
  • linux资料总章2.1 1.0写的不好抱歉 但是2.0已经改了很多 但是错误还是无法避免 以后资料会慢慢更新 大...
    数据革命阅读 12,218评论 2 33
  • 从三月份找实习到现在,面了一些公司,挂了不少,但最终还是拿到小米、百度、阿里、京东、新浪、CVTE、乐视家的研发岗...
    时芥蓝阅读 42,366评论 11 349
  • 我是个忧郁的人,常常左手托着左腮,右手托着右腮,仰望天空四十五度,眼神深邃,目光忧郁,连鼻孔呼出的二氧化碳都将周围...
    半诗阅读 362评论 4 5
  • 去年生病觉得整个人都垮掉了,什么都没办法做,去门口健身房办了卡,想要把身体锻炼好,练了快一年的时间没有什么长进...
    87ad4e183399阅读 198评论 0 0