当"ssh"被执行时,bash while循环结束执行.在循环体内 [英] Bash while loop ends execution when "ssh" is in loop body
问题描述
请问任何人解释一下为什么在主体中执行 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 --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
也使用标准输入.尝试用 cat
或 nl
替换 ssh $ HOST主机名
,以从概念上理解为什么它不起作用.命令使用完输入后, 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
这篇关于当"ssh"被执行时,bash while循环结束执行.在循环体内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!