Bash while 循环在“ssh"时结束执行在循环体中 [英] Bash while loop ends execution when "ssh" is in loop body

查看:28
本文介绍了Bash while 循环在“ssh"时结束执行在循环体中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你们中的任何人都可以解释为什么当 ssh 在它的主体中执行时,下面的 bash while 循环在第一次迭代后结束执行吗?

Could anyone of you explain why the following bash while loop ends execution after the first iteration when ssh is executed in it's body, please?

输入文件:

$ cat hosts
192.168.223.21     miner01
192.168.223.23     miner03

  • 虽然没有 ssh - 两次迭代:
  • $ while IFS=' ' read -r IP HOST; do echo "ip=$IP hostname=$HOST"; done < hosts
    ip=192.168.223.21 hostname=miner01
    ip=192.168.223.23 hostname=miner03
    $
    

    • 虽然在主体中使用 ssh - 一次迭代:
    • $ while IFS=' ' read -r IP HOST; do echo "ip=$IP hostname=$HOST"; ssh $HOST hostname ; done < hosts
      ip=192.168.223.21 hostname=miner01
      miner01
      $
      

      我也用 set -x 执行了它,但我看不到这种行为的原因:

      I also executed it with set -x but I can't see the reason for such behavior:

      $ while IFS=" " read -r IP HOST; do echo "ip=$IP hostname=$HOST"; ssh $HOST hostname; done < hosts
      while IFS=" " read -r IP HOST; do echo "ip=$IP hostname=$HOST"; ssh $HOST hostname; done < hosts
      + IFS=' '
      + read -r IP HOST
      + echo 'ip=192.168.223.21 hostname=miner01'
      ip=192.168.223.21 hostname=miner01
      + ssh miner01 hostname
      miner01
      + IFS=' '
      + read -r IP HOST
      $
      

      Bash 版本:

      $ bash --version
      bash --version
      GNU bash, version 5.0.3(1)-release (x86_64-pc-linux-gnu)
      Copyright (C) 2019 Free Software Foundation, Inc.
      License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
      

      推荐答案

      ssh 也使用标准输入.尝试用 catnl 替换 ssh $HOST hostname,从概念上理解为什么它不起作用.命令使用完输入后,while 结束,因为没有其他内容可读取.

      ssh also consumes standard input. Try to replace ssh $HOST hostname with cat or nl, to understand conceptually why it does not work. After the command consumes the input, while ends since there is nothing else to read.

      由于您不需要 ssh 来使用 stdin,因此将其重定向.这有效:

      Since you do not need ssh to consume stdin, redirect it. This works:

      while IFS=" " read -r IP HOST; do
        echo "ip=$IP hostname=$HOST"
        ssh $HOST hostname < /dev/null
      done < hosts
      

      这篇关于Bash while 循环在“ssh"时结束执行在循环体中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆