首页 > shellscript 循环执行代码,但是每次执行一次以后就退出了?

shellscript 循环执行代码,但是每次执行一次以后就退出了?

while read $HOSTNAME
do
    ssh root@$HOSTNAME "poweroff"
done < host.log

host.log 中的内容:
192.168.122.1
192.168.122.2
192.168.122.3

机器配置过ssh互信

执行那个后发现每次只能关闭一台机器脚本就退出了。需要再次执行才能关闭后面的机器,请问是为什么?谢谢


去掉while read $HOSTNAME中的$

while read HOSTNAME
do
ssh root@$HOSTNAME "poweroff"
done < host.log


或者写 ssh -n 吧。出现这种情况的原因是,ssh 读取了你余下的 stdin。

所以我尽量不使用 while + 重定向读取数据,要读也用另外的文件描述符来读。stdin 很容易被别的命令读走的。


perl -ne 'system q/ssh/, q/root@/.$_,q/poweroff/' host.log #这样该可以


在这行写成这样试试: ssh root@$HOSTNAME "poweroff" < /dev/null

【热门文章】
【热门文章】