0

I want to get all the servers' time with ssh, but my script only loops once and then exit, what's the reason?

servers.txt

192.168.1.123
192.168.1.124
192.168.1.125
192.168.1.126

gettime.sh

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

done < "servers.txt"

OUTPUT

Tue Feb  3 09:56:54 CST 2015
Hunter Zhao
  • 4,589
  • 2
  • 25
  • 39
  • BTW, I'd consider doing this in parallel rather than serially -- otherwise, you'll get different results just because of time passing between when you start running the command against your various servers. For instance: `while read host; do (remotedate=$(ssh -n "$host" date); echo "$host: $remotedate") & done` will start new ssh sessions as fast as it can read names from the file and fork off subshells for each line read, rather than waiting for each to return before reading the next. – Charles Duffy Feb 03 '15 at 02:52

1 Answers1

4

This happens because ssh starts reading the input you intended for your loop. You can add < /dev/null to prevent it:

#!/bin/bash
while read host
do
    ssh root@${host} date < /dev/null
done < "servers.txt"

The same thing tends to happen with ffmpeg and mplayer, and can be solved the same way.


PS: This and other issues are automatically caught by shellcheck:

In yourscript line 4:
    ssh root@${host} date
    ^-- SC2095: Add < /dev/null to prevent ssh from swallowing stdin.
that other guy
  • 116,971
  • 11
  • 170
  • 194