Shell 脚本 while 只循环一次

Hun*_*hao 0 linux bash shell

我想通过 ssh 获取所有服务器的时间,但我的脚本只循环一次然后退出,是什么原因?

服务器.txt

192.168.1.123
192.168.1.124
192.168.1.125
192.168.1.126
Run Code Online (Sandbox Code Playgroud)

获取时间.sh

#!/bin/bash
while read host
do
    ssh root@${host} date

done < "servers.txt"
Run Code Online (Sandbox Code Playgroud)

输出

Tue Feb  3 09:56:54 CST 2015
Run Code Online (Sandbox Code Playgroud)

tha*_*guy 5

发生这种情况是因为ssh开始读取您打算用于循环的输入。您可以添加< /dev/null来防止它:

#!/bin/bash
while read host
do
    ssh root@${host} date < /dev/null
done < "servers.txt"
Run Code Online (Sandbox Code Playgroud)

同样的事情往往会发生在ffmpeg和 上mplayer,并且可以用同样的方式解决。


PS:这个问题和其他问题会被shellcheck自动捕获:

In yourscript line 4:
    ssh root@${host} date
    ^-- SC2095: Add < /dev/null to prevent ssh from swallowing stdin.
Run Code Online (Sandbox Code Playgroud)